1 package com.dotmarketing.portlets.usermanager.action; 2 3 import java.io.BufferedReader ; 4 import java.io.File ; 5 import java.io.FileReader ; 6 import java.io.IOException ; 7 import java.io.LineNumberReader ; 8 import java.util.Date ; 9 import java.util.Iterator ; 10 import java.util.List ; 11 import java.util.Map ; 12 import java.util.StringTokenizer ; 13 14 import javax.portlet.ActionRequest; 15 import javax.portlet.ActionResponse; 16 import javax.portlet.PortletConfig; 17 import javax.portlet.PortletSession; 18 import javax.portlet.RenderRequest; 19 import javax.portlet.RenderResponse; 20 import javax.portlet.WindowState; 21 import javax.servlet.ServletOutputStream ; 22 import javax.servlet.http.HttpServletRequest ; 23 import javax.servlet.http.HttpServletResponse ; 24 import javax.servlet.http.HttpSession ; 25 import javax.servlet.jsp.PageContext ; 26 27 import org.apache.struts.action.ActionForm; 28 import org.apache.struts.action.ActionForward; 29 import org.apache.struts.action.ActionMapping; 30 31 import com.dotmarketing.beans.UserProxy; 32 import com.dotmarketing.cms.factories.PublicAddressFactory; 33 import com.dotmarketing.cms.factories.PublicEncryptionFactory; 34 import com.dotmarketing.cms.factories.PublicUserFactory; 35 import com.dotmarketing.db.DotHibernate; 36 import com.dotmarketing.factories.InodeFactory; 37 import com.dotmarketing.factories.UserProxyFactory; 38 import com.dotmarketing.portal.struts.DotPortletAction; 39 import com.dotmarketing.portlets.mailinglists.factories.MailingListFactory; 40 import com.dotmarketing.portlets.mailinglists.model.MailingList; 41 import com.dotmarketing.portlets.usermanager.factories.UserManagerListBuilderFactory; 42 import com.dotmarketing.portlets.usermanager.struts.UserManagerListSearchForm; 43 import com.dotmarketing.util.Config; 44 import com.dotmarketing.util.Logger; 45 import com.dotmarketing.util.UtilMethods; 46 import com.dotmarketing.util.Validator; 47 import com.dotmarketing.util.WebKeys; 48 import com.liferay.portal.ejb.UserLocalManagerUtil; 49 import com.liferay.portal.model.Address; 50 import com.liferay.portal.model.User; 51 import com.liferay.portal.util.Constants; 52 import com.liferay.portal.util.PortalUtil; 53 import com.liferay.portlet.ActionResponseImpl; 54 import com.liferay.portlet.RenderRequestImpl; 55 import com.liferay.util.FileUtil; 56 import com.liferay.util.servlet.SessionMessages; 57 import com.liferay.util.servlet.UploadPortletRequest; 58 60 66 public class ViewUserManagerListAction extends DotPortletAction { 67 68 71 public ActionForward render( 72 ActionMapping mapping, ActionForm form, PortletConfig config, 73 RenderRequest req, RenderResponse res) 74 throws Exception { 75 76 HttpServletRequest request = ((RenderRequestImpl)req).getHttpServletRequest(); 77 78 String cmd = req.getParameter("cmd"); 79 80 UserManagerListSearchForm searchForm = (UserManagerListSearchForm) form; 81 82 83 84 try { 85 User user = _getUser(req); 87 88 if (com.liferay.portal.util.Constants.DELETE.equals(cmd)) { 90 try { 91 _delete(form, req, res); 92 cmd = com.liferay.portal.util.Constants.SEARCH; 93 } catch (Exception e) { 94 _handleException(e, req, mapping); 95 } 96 } 97 98 List list = MailingListFactory.getAllMailingLists(); 99 req.setAttribute(WebKeys.MAILING_LIST_VIEW, list); 100 101 RenderRequestImpl reqImpl = (RenderRequestImpl) req; 102 HttpServletRequest httpReq = reqImpl.getHttpServletRequest(); 103 HttpSession session = httpReq.getSession(); 104 if(session.getAttribute(WebKeys.USERMANAGERLISTFORM) != null){ 105 req.setAttribute(WebKeys.USERMANAGERLISTFORM, searchForm); 107 req.setAttribute("page", 1); 108 _doSearch(req,searchForm); 109 session.removeAttribute(WebKeys.USERMANAGERLISTFORM); 110 return mapping.findForward("portlet.ext.usermanager.view_usermanagerlist"); 111 } 112 113 if (!Validator.validate(request, searchForm, mapping)) { 114 if (req.getWindowState().equals(WindowState.NORMAL)) { 115 return mapping.findForward("portlet.ext.usermanager.view"); 116 } 117 else { 118 if (cmd != null && cmd.equals(com.liferay.portal.util.Constants.SEARCH)) { 119 _doSearch(req, searchForm); 120 } 121 req.setAttribute(WebKeys.USERMANAGERLISTFORM, searchForm); 122 123 124 return mapping.findForward("portlet.ext.usermanager.view_usermanagerlist"); 125 } 126 } 127 if (req.getWindowState().equals(WindowState.NORMAL)) { 128 return mapping.findForward("portlet.ext.usermanager.view"); 129 } 130 else { 131 if (cmd != null && cmd.equals(com.liferay.portal.util.Constants.SEARCH)) { 132 _doSearch(req, searchForm); 133 } 134 req.setAttribute(WebKeys.USERMANAGERLISTFORM, searchForm); 135 return mapping.findForward("portlet.ext.usermanager.view_usermanagerlist"); 136 } 137 } 138 catch (Exception e) { 139 req.setAttribute(PageContext.EXCEPTION, e); 140 return mapping.findForward(Constants.COMMON_ERROR); 141 } 142 } 143 144 public void processAction( 145 ActionMapping mapping, ActionForm form, PortletConfig config, 146 ActionRequest req, ActionResponse res) 147 throws Exception { 148 String cmd = req.getParameter(com.liferay.portal.util.Constants.CMD); 149 UserManagerListSearchForm searchForm = (UserManagerListSearchForm) form; 150 if(cmd != null && cmd.equals("exportExcel")){ 151 _exportExcel(req, res,config,form); 152 } 153 154 if (com.liferay.portal.util.Constants.ADD.equals(cmd)) { 155 try { 156 _loadUserCSVFiles(form, req, res); 157 } catch (Exception e) { 158 _handleException(e, req); 159 } 160 res.setRenderParameter("cmd", com.liferay.portal.util.Constants.SEARCH); 161 } 162 163 if (com.liferay.portal.util.Constants.SAVE.equals(cmd)) { 165 try { 166 _saveMarketingList(form,req,res, "0"); 167 } 168 catch (Exception e) { 169 _handleException(e,req); 170 } 171 } 172 if (com.liferay.portal.util.Constants.UPDATE.equals(cmd)) { 173 try { 174 if (searchForm.getUsermanagerListInode().equals("")) { 175 SessionMessages.add(req, "message", "message.mailinglistbuilder.nolist"); 176 } else { 177 _saveMarketingList(form,req,res, searchForm.getUsermanagerListInode()); 178 } 179 } 180 catch (Exception e) { 181 _handleException(e,req); 182 } 183 } 184 if (com.liferay.portal.util.Constants.EDIT.equals(cmd)) { 185 186 try { 187 if (searchForm.getUsermanagerListInode().equals("")) { 188 SessionMessages.add(req, "message", "message.mailinglistbuilder.nolist"); 189 } else { 190 _removeFromMarketingList(form,req,res, searchForm.getUsermanagerListInode()); 191 } 192 } 193 catch (Exception e) { 194 _handleException(e,req); 195 } 196 } 197 PortletSession sess = req.getPortletSession(); 198 String [][] matchesArray = (String [][])sess.getAttribute(WebKeys.USERMANAGERLIST); 199 req.setAttribute(WebKeys.USERMANAGERLIST, matchesArray); 200 req.setAttribute(WebKeys.USERMANAGERLISTFORM, searchForm); 201 202 sess.setAttribute(WebKeys.USERMANAGERLIST, matchesArray); 203 sess.setAttribute(WebKeys.USERMANAGERLISTFORM, searchForm); 204 205 setForward(req, "portlet.ext.usermanager.view_usermanagerlist"); 206 207 } 208 209 private void _delete(ActionForm form, RenderRequest req, RenderResponse res) 211 throws Exception { 212 213 String userId = req.getParameter("userID"); 214 String companyId = com.dotmarketing.cms.factories.PublicCompanyFactory.getDefaultCompany().getCompanyId(); 215 216 User user = UserLocalManagerUtil.getUserById(companyId, userId); 217 UserProxy userProxy = UserProxyFactory.getUserProxy(user); 218 219 InodeFactory.deleteInode(userProxy); 221 UserLocalManagerUtil.deleteUser(userId); 223 224 SessionMessages.add(req, "message", "message.usermanager.deleted"); 225 226 } 227 228 232 private void _doSearch(RenderRequest req, UserManagerListSearchForm searchForm) throws Exception { 233 234 PortletSession session = req.getPortletSession(); 235 236 String page = req.getParameter("page"); 237 if (!UtilMethods.isSet(page)) 238 page = (String )session.getAttribute("page"); 239 else 240 session.setAttribute("page", page); 241 242 if (!UtilMethods.isSet(page)) 243 page = "1"; 244 245 req.setAttribute("page", page); 246 247 int pageInt = 1; 248 try { 249 pageInt = Integer.parseInt(page); 250 } catch (NumberFormatException e) { } 251 int perPage = Config.getIntProperty("USERMANAGER_PER_PAGE"); 252 int offset = (pageInt - 1) * perPage; 253 int endRecord = offset + perPage; 254 255 searchForm.setStartRow(offset); 256 searchForm.setMaxRow(endRecord); 257 258 List matches = UserManagerListBuilderFactory.doSearch(searchForm); 259 searchForm.setStartRow(0); 260 searchForm.setMaxRow(0); 261 int count = UserManagerListBuilderFactory.doSearch(searchForm).size(); 262 263 String [][] matchesArray = new String [matches.size()][13]; 264 Iterator it = matches.iterator(); 265 for (int i = 0; it.hasNext(); i++) { 266 267 User user = null; 268 269 String userId = (String ) ((Map )it.next()).get("userid"); 270 271 user = UserLocalManagerUtil.getUserById(userId); 272 273 List addresses = user.getAddresses(); 274 Address address = null; 275 if (addresses.size() > 0) { 276 address = (Address) addresses.get(0); 277 } 278 matchesArray[i][0] = userId; 279 matchesArray[i][1] = user.getFirstName(); 280 matchesArray[i][2] = user.getMiddleName(); 281 matchesArray[i][3] = user.getLastName(); 282 matchesArray[i][4] = user.getEmailAddress(); 283 matchesArray[i][5] = (address == null)?"":address.getStreet1(); 284 matchesArray[i][6] = (address == null)?"":address.getStreet2(); 285 matchesArray[i][7] = (address == null)?"":address.getCity(); 286 matchesArray[i][8] = (address == null)?"":address.getState(); 287 matchesArray[i][9] = (address == null)?"":address.getZip(); 288 matchesArray[i][10] = (address == null)?"":address.getCountry(); 289 matchesArray[i][11] = (address == null)?"":address.getPhone(); 290 matchesArray[i][12] = UtilMethods.htmlDateToHTMLTime(user.getCreateDate()); 291 } 292 293 294 295 296 297 req.setAttribute(WebKeys.USERMANAGERLIST, matchesArray); 298 PortletSession sess = req.getPortletSession(); 299 sess.setAttribute(WebKeys.USERMANAGERLIST, matchesArray); 300 301 req.setAttribute(WebKeys.USERMANAGERLISTCOUNT, count); 302 sess.setAttribute(WebKeys.USERMANAGERLISTCOUNT, count); 303 304 305 306 307 308 } 309 310 @SuppressWarnings ("unchecked") 311 private void _exportExcel(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { 312 313 PortletSession session = req.getPortletSession(); 315 316 ActionResponseImpl resImpl = (ActionResponseImpl)res; 317 HttpServletResponse httpRes = resImpl.getHttpServletResponse(); 318 319 String [][] matches = (String [][])session.getAttribute(com.dotmarketing.util.WebKeys.USERMANAGERLIST); 320 if (matches == null) matches = new String [0][0]; 321 322 httpRes.setContentType("application/octet-stream"); 323 httpRes.setHeader("Content-Disposition", "attachment; filename=\"users_" + UtilMethods.dateToHTMLDate(new Date (),"M_d_yyyy") +".csv\""); 324 325 ServletOutputStream out = httpRes.getOutputStream(); 326 try { 327 328 if (matches.length > 0) { 329 330 out.print("First Name,Last Name,Email Address,Address Street1,Address Street2,City,State,Country,Zip,Phone"); 331 out.print("\r\n"); 332 for (int i=0; i < matches.length; i++) { 333 String [] match = matches[i]; 334 out.print((match[1] == null ? "," : "\"" + match[1] + "\",")); 335 out.print((match[3] == null ? "," : "\"" + match[3] + "\",")); 336 out.print((match[4] == null ? "," : "\"" + match[4] + "\",")); 337 out.print((match[5] == null ? "," : "\"" + match[5] + "\",")); 338 out.print((match[6] == null ? "," : "\"" + match[6] + "\",")); 339 out.print((match[7] == null ? "," : "\"" + match[7] + "\",")); 340 out.print((match[8] == null ? "," : "\"" + match[8] + "\",")); 341 out.print((match[10] == null ? "," : "\"" + match[10] + "\",")); 342 out.print((match[9] == null ? "," : "\"" + match[9] + "\",")); 343 out.print((match[11] == null ? "," : "\"" + match[11] + "\",")); 344 out.print("\r\n"); 345 } 346 }else { 347 out.print("There are no Users to show"); 348 out.print("\r\n"); 349 } 350 out.flush(); 351 out.close(); 352 DotHibernate.closeSession(); 353 }catch(Exception p){ 354 out.print("There are no Users to show"); 355 out.print("\r\n"); 356 out.flush(); 357 out.close(); 358 DotHibernate.closeSession(); 359 } 360 } 361 362 private void _loadUserCSVFiles(ActionForm form, ActionRequest req, ActionResponse res) 363 throws Exception { 364 365 UserManagerListSearchForm userForm = (UserManagerListSearchForm) form; 366 String [] arrayUserIds; 367 UploadPortletRequest uploadReq = PortalUtil.getUploadPortletRequest(req); 368 java.io.File uploadedFile = uploadReq.getFile("newUsersFile"); 369 byte[] bytes = FileUtil.getBytes(uploadedFile); 370 StringBuffer returnMessage = new StringBuffer (); 371 372 if(bytes!=null && bytes.length >0){ 373 374 FileReader freader = new FileReader (uploadedFile); 375 LineNumberReader lnreader = new LineNumberReader (freader); 376 List lines = UtilMethods.specialSplit(lnreader, ",", "\""); 377 378 if (!_validateCSVFile(uploadedFile)) { 379 SessionMessages.add(req, "message", "message.mailinglist.invalidCSVFile"); 380 return; 381 } 382 383 int init = 0; 385 String companyId = com.dotmarketing.cms.factories.PublicCompanyFactory.getDefaultCompany().getCompanyId(); 390 arrayUserIds = new String [lines.size()]; 391 int userCreated = 0; 392 for (int k=init; k < lines.size(); k++) { 393 394 String [] lineTok = (String []) lines.get(k); 395 396 String firstName = ""; 397 String middleName = ""; 398 String lastName = ""; 399 String email = ""; 400 String password = ""; 401 String dateOfBirthday = ""; 402 String street1 = ""; 403 String street2 = ""; 404 String city = ""; 405 String state = ""; 406 String zip = ""; 407 String country = ""; 408 String phone = ""; 409 String fax = ""; 410 String cell = ""; 411 412 try { 413 414 int i = 0; 415 firstName = lineTok[i++]; 416 middleName = lineTok[i++]; 417 lastName = lineTok[i++]; 418 email = lineTok[i++]; 419 420 if (UtilMethods.isValidEmail(email)) { 421 422 password = lineTok[i++]; 423 dateOfBirthday = lineTok[i++]; 424 Date birthday = UtilMethods.htmlToDate(dateOfBirthday); 425 birthday = (birthday == null)?(new Date ()):birthday; 426 427 street1 = lineTok[i++]; 428 street2 = lineTok[i++]; 429 city = lineTok[i++]; 430 state = lineTok[i++]; 431 zip = lineTok[i++]; 432 country = lineTok[i++]; 433 phone = lineTok[i++]; 434 fax = lineTok[i++]; 435 cell = lineTok[i++]; 436 437 if(firstName.equalsIgnoreCase("")) { 438 returnMessage.append("Missing First Name on line # "+(k+1)+"<br>"); 439 continue; 440 } 441 if(lastName.equalsIgnoreCase("")) { 442 returnMessage.append("Missing Last Name on line # "+(k+1)+"<br>"); 443 continue; 444 } 445 if(email.equalsIgnoreCase("")) { 446 returnMessage.append("Missing Email Address on line # "+(k+1)+"<br>"); 447 continue; 448 } 449 if(street1.equalsIgnoreCase("")) { 450 returnMessage.append("Missing Address Street 1 on line # "+(k+1)+"<br>"); 451 continue; 452 } 453 if(city.equalsIgnoreCase("")) { 454 returnMessage.append("Missing Address City on line # "+(k+1)+"<br>"); 455 continue; 456 } 457 if(state.equalsIgnoreCase("")) { 458 returnMessage.append("Missing Address State on line # "+(k+1)+"<br>"); 459 continue; 460 } 461 if(zip.equalsIgnoreCase("")) { 462 returnMessage.append("Missing Address Zip on line # "+(k+1)+"<br>"); 463 continue; 464 } 465 if(country.equalsIgnoreCase("")) { 466 returnMessage.append("Missing Address Country on line # "+(k+1)+"<br>"); 467 continue; 468 } 469 470 if(validateUniqueEmail(email, companyId)) { 471 User user = PublicUserFactory.getInstance(); 472 user.setCompanyId(companyId); 473 user.setActive(true); 474 user.setSkinId("01"); 475 user.setCreateDate(new Date ()); 476 user.setGreeting("Welcome, "+firstName+" "+lastName+"!"); 477 user.setFirstName(firstName); 478 user.setMiddleName(middleName); 479 user.setLastName(lastName); 480 user.setNickName(""); 481 user.setNew(true); 482 user.setLanguageId("en_US"); 483 user.setTimeZoneId("US/Eastern"); 484 user.setResolution("1024x768"); 485 user.setRefreshRate("900"); 486 user.setLayoutIds(""); 487 user.setEmailAddress(email); 488 user.setBirthday(birthday); 489 490 if (!UtilMethods.isSet(password)) { 491 password = PublicEncryptionFactory.getRandomPassword(); 492 } 493 user.setPassword(PublicEncryptionFactory.digestString(password)); 494 user.setPasswordEncrypted(true); 495 496 PublicUserFactory.save(user); 497 498 UserProxy userProxy = UserProxyFactory.getUserProxy(user); 499 long userProxyInode = userProxy.getInode(); 500 userProxy = (UserProxy) InodeFactory.getInode(userProxyInode, UserProxy.class); 501 userProxy.setInode(userProxyInode); 502 userProxy.setUserId(user.getUserId()); 503 UserProxyFactory.saveUserProxy(userProxy); 504 505 Date today = new Date (); 506 507 Address address = PublicAddressFactory.getInstance(); 508 address.setUserName(user.getFullName()); 509 address.setCompanyId(companyId); 510 address.setUserId(user.getUserId()); 511 address.setCreateDate(today); 512 address.setModifiedDate(today); 513 address.setPriority(1); 514 address.setClassName(user.getClass().getName()); 515 address.setClassPK(user.getUserId()); 516 address.setDescription("Primary"); 517 address.setStreet1(street1); 518 address.setStreet2(street2); 519 address.setCity(city); 520 address.setState(state); 521 address.setZip(zip); 522 address.setPhone(phone); 523 address.setFax(fax); 524 address.setCell(cell); 525 526 PublicAddressFactory.save(address); 527 528 arrayUserIds[k] = user.getUserId(); 529 userCreated++; 530 531 } 532 else { 533 returnMessage.append("Duplicated Email: "+email+" - line # "+(k+1)+"<br>"); 535 } 536 537 } 538 539 } catch (Exception e) { 540 returnMessage.append("Error creating user with email: "+email+" - line # "+(k+1)+"<br>"); 541 } 542 543 544 } 545 returnMessage.append(userCreated+" Users Created"); 546 547 SessionMessages.add(req, "message", returnMessage.toString()); 548 userForm.setArrayUserIds(arrayUserIds); 549 DotHibernate.flush(); 550 551 } 552 553 } 554 555 private boolean _validateCSVFile (File f) throws IOException { 556 BufferedReader reader = new BufferedReader (new FileReader (f)); 557 String line = reader.readLine(); 558 for (;line!= null;line = reader.readLine()) { 559 StringTokenizer st = new StringTokenizer (line, ",", true); 560 if (st.countTokens() <= 1) 561 return false; 562 } 563 return true; 564 } 565 566 private boolean validateUniqueEmail(String emailAddress, String companyId) 567 { 568 boolean returnValue = true; 569 User member = null; 570 if (UtilMethods.isSet(emailAddress)) 571 { 572 try 573 { 574 member = UserLocalManagerUtil.getUserByEmailAddress(companyId,emailAddress); 575 } 576 catch(Exception ex) 577 { 578 Logger.debug(this,ex.toString()); 579 } 580 } 581 if(!(member == null)) 582 { 583 returnValue = false; 584 } 585 return returnValue; 586 } 587 588 private void _saveMarketingList(ActionForm form, ActionRequest req, ActionResponse res, String mailingListInode) throws Exception { 589 590 User user = _getUser(req); 591 UserManagerListSearchForm mlForm = (UserManagerListSearchForm) form; 592 PortletSession sess = req.getPortletSession(); 593 String [][] matchesArray = (String [][])sess.getAttribute(WebKeys.USERMANAGERLIST); 594 595 MailingList ml = (MailingList) InodeFactory.getInode(mailingListInode,MailingList.class); 597 String cmd = req.getParameter(com.liferay.portal.util.Constants.CMD); 598 if (com.liferay.portal.util.Constants.SAVE.equals(cmd)) { 599 ml.setTitle(mlForm.getUsermanagerListTitle()); 600 ml.setPublicList(mlForm.isAllowPublicToSubscribe()); 601 ml.setUserId(user.getUserId()); 602 } 603 InodeFactory.saveInode(ml); 604 mlForm.setUsermanagerListTitle(""); 605 mlForm.setAllowPublicToSubscribe(false); 606 607 for (int i = 0; i < matchesArray.length; i++) { 609 User userSubscriber = PublicUserFactory.findUserByUserId(matchesArray[i][0]); 610 UserProxy s = UserProxyFactory.getUserProxy(userSubscriber); 611 612 if (s.getInode() == 0) { 613 s.setUserId(userSubscriber.getUserId()); 614 s.setLastResult(0); 615 InodeFactory.saveInode(s); 616 } 617 618 ml.addChild(s); 619 } 620 621 DotHibernate.flush(); 622 DotHibernate.closeSession(); 623 624 ml.setSubscriberCount(InodeFactory.getChildrenClass(ml, UserProxy.class).size()); 625 InodeFactory.saveInode(ml); 626 627 SessionMessages.add(req, "message", "message.mailinglistbuilder.save"); 628 } 629 630 private void _removeFromMarketingList(ActionForm form, ActionRequest req, ActionResponse res, String mailingListInode) throws Exception { 631 632 PortletSession sess = req.getPortletSession(); 633 String [][] matchesArray = (String [][])sess.getAttribute(WebKeys.USERMANAGERLIST); 634 635 MailingList ml = (MailingList) InodeFactory.getInode(mailingListInode,MailingList.class); 637 638 for (int i = 0; i < matchesArray.length; i++) { 640 User userSubscriber = PublicUserFactory.findUserByUserId(matchesArray[i][0]); 641 UserProxy s = UserProxyFactory.getUserProxy(userSubscriber); 642 if (s.getInode() > 0) 643 ml.deleteChild(s); 644 } 645 646 DotHibernate.flush(); 647 DotHibernate.closeSession(); 648 649 ml.setSubscriberCount(InodeFactory.getChildrenClass(ml, UserProxy.class).size()); 650 InodeFactory.saveInode(ml); 651 652 SessionMessages.add(req, "message", "message.mailinglistbuilder.subscribers.removed"); 653 } 654 655 } | Popular Tags |