Advertisement
Guest User

Untitled

a guest
Oct 15th, 2017
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.50 KB | None | 0 0
  1. package com.fluig.identity.scripts.impl;
  2.  
  3. import java.net.MalformedURLException;
  4. import java.net.URL;
  5. import java.rmi.RemoteException;
  6. import java.util.Date;
  7. import java.util.EnumMap;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Properties;
  11.  
  12. import javax.mail.Authenticator;
  13. import javax.mail.Message;
  14. import javax.mail.PasswordAuthentication;
  15. import javax.mail.Session;
  16. import javax.mail.Transport;
  17. import javax.mail.internet.InternetAddress;
  18. import javax.mail.internet.MimeMessage;
  19.  
  20. import org.apache.commons.lang.StringUtils;
  21.  
  22. import com.beust.jcommander.Parameter;
  23. import com.beust.jcommander.Parameters;
  24. import com.beust.jcommander.ParametersDelegate;
  25. import com.fluig.identity.ScriptInterface;
  26. import com.fluig.identity.scripts.utils.DateScriptUtils;
  27. import com.fluig.identity.scripts.utils.UserAccount;
  28. import com.fluig.identity.util.FileLoggerUtil;
  29. import com.fluig.identity.util.FileUtils;
  30. import com.totvslabs.idm.common.model.CompanyDTO;
  31. import com.totvslabs.idm.common.model.EmailTemplateDTO;
  32. import com.totvslabs.idm.common.model.UserAccountDTO;
  33. import com.totvslabs.idm.common.model.UserCompanyAccountDTO;
  34. import com.totvslabs.idm.common.model.UserLiteDTO;
  35. import com.totvslabs.idm.common.util.DateFormatUtils;
  36. import com.totvslabs.idm.common.util.SupportedLocales;
  37. import com.totvslabs.idm.common.util.UserOriginEnum;
  38. import com.fluig.identity.core.enums.UserStatusEnum;
  39. import com.totvslabs.idm.core.email.EmailInformation;
  40. import com.totvslabs.idm.db.dbInterface.DBCompanyService;
  41. import com.totvslabs.idm.db.exception.AcquireLockException;
  42. import com.totvslabs.idm.db.services.DBCompanyServiceImpl;
  43. import com.totvslabs.idm.db.services.DBUserServiceImpl;
  44. import com.totvslabs.idm.utils.ServerConstants;
  45.  
  46. /**
  47.  * Created by tiago.jensen on 09/02/2017.
  48.  */
  49. @Parameters(commandNames = {"activateAllCompanyUsers"}, commandDescription = "Activate all company users")
  50. public class ActivateAllCompanyUsersScript extends ScriptInterface {
  51.     public static final ActivateAllCompanyUsersScript instance = new ActivateAllCompanyUsersScript();
  52.  
  53.     private final DBUserServiceImpl userService = new DBUserServiceImpl();
  54.     private final DBCompanyService dbCompanyService = new DBCompanyServiceImpl();
  55.     int totalUsers = 0;
  56.     StringBuilder stringBuilder = new StringBuilder();
  57.     String lineSeparator = System.lineSeparator();
  58.  
  59.     @ParametersDelegate
  60.     protected UserAccount userAccountUtil = new UserAccount(bucket);
  61.  
  62.     @Parameter(names = {"--companyId", "-C"}, description = "Company ID", required = true)
  63.     protected String companyId;
  64.  
  65.     @Parameter(names = {"--userId", "-U"}, description = "User ID")
  66.     protected String userId = null;
  67.  
  68.     @Parameter(names = {"--activateNonADUsers", "-A"}, description = "Activate Non AD Users (yes or y to activate)")
  69.     protected String activateNonADUsers = "no";
  70.     protected boolean isActivateNonADUsers = false;
  71.  
  72.     @Parameter(names = {"--sendMail", "-M"}, description = "Activated user should receive notification mail (yes or y to send mail)")
  73.     protected String sendMail = "no";
  74.     protected boolean isSendMail = false;
  75.  
  76.     @Parameter(names = {"--to", "-T"}, description = "Email address to send test")
  77.     protected String to;
  78.  
  79.     @Override
  80.     public Object call() throws Exception {
  81.         this.scriptLog(FileLoggerUtil.TOPIC_SPACER);
  82.         this.scriptLog("Executing ActivateAllCompanyUsersScript...");
  83.         this.scriptLog("Params");
  84.         this.scriptLog("  writeChanges: "+writeChanges);
  85.         this.scriptLog("  companyId: "+companyId);
  86.         this.scriptLog("  userId: "+userId);
  87.         this.scriptLog("  activateNonADUsers: "+activateNonADUsers);
  88.         this.scriptLog("  sendMail: "+sendMail);
  89.         this.scriptLog("  to: "+to);
  90.         this.scriptLog("Date: "+ DateFormatUtils.getStringDateBR(new Date()));
  91.         this.scriptLog(FileLoggerUtil.TOPIC_SPACER);
  92.         propertiesSetup();
  93.         if ("yes".equalsIgnoreCase(activateNonADUsers) ||
  94.                 "y".equalsIgnoreCase(activateNonADUsers)) {
  95.             isActivateNonADUsers = true;
  96.         }
  97.         if ("yes".equalsIgnoreCase(sendMail) ||
  98.                 "y".equalsIgnoreCase(sendMail)) {
  99.             isSendMail = true;
  100.         }
  101.         UserCompanyAccountDTO userCompanyAccountDTO;
  102.         CompanyDTO companyDTO = dbCompanyService.getCompany(companyId);
  103.         if (companyDTO == null) {
  104.             this.scriptLog("[ERROR] COMPANY NOT FOUND!!!");
  105.             return null;
  106.         }
  107.  
  108.         if (StringUtils.isNotBlank(to)) {
  109.             UserCompanyAccountDTO tempUser = new UserCompanyAccountDTO();
  110.             tempUser.setEmailAddress(to);
  111.             tempUser.setFirstName("Test");
  112.             tempUser.setFirstName("Sendmail");
  113.             this.sendMail(companyDTO, tempUser);
  114.             return null;
  115.         }
  116.  
  117.         if (userId != null) {
  118.             userCompanyAccountDTO = userAccountUtil.getUserCompanyAccountById(userId, companyId);
  119.             if (userCompanyAccountDTO != null) {
  120.                 this.activateUser(companyDTO, userCompanyAccountDTO, 1);
  121.             } else {
  122.                 this.scriptLog("[ERROR] USER COMPANY ACCOUNT NOT FOUND! ("+companyId+"_"+userId+")");
  123.             }
  124.         } else {
  125.             HashMap<String, UserLiteDTO> allCompanyUserAccounts = userAccountUtil.getAllCompanyUserAccounts(companyId);
  126.             if (allCompanyUserAccounts != null &&
  127.                     !allCompanyUserAccounts.isEmpty()) {
  128.                 int i = 0;
  129.                 this.totalUsers = allCompanyUserAccounts.size();
  130.                 for (String key : allCompanyUserAccounts.keySet()) {
  131.                     i++;
  132.                     userCompanyAccountDTO = userAccountUtil.getUserCompanyAccountById(key, companyId);
  133.                     if (userCompanyAccountDTO != null) {
  134.                         this.activateUser(companyDTO, userCompanyAccountDTO, i);
  135.                     } else {
  136.                         this.scriptLog("[ERROR] USER COMPANY ACCOUNT NOT FOUND! ("+companyId+"_"+key+")");
  137.                     }
  138.                     this.scriptLog(FileLoggerUtil.LINE_SPACER);
  139.                 }
  140.             } else {
  141.                 this.scriptLog("[ERROR] USER COMPANY ACCOUNT LIST NOT FOUND! ("+companyId+")");
  142.             }
  143.         }
  144.         this.scriptLog(FileLoggerUtil.TOPIC_SPACER);
  145.         System.out.println(stringBuilder.toString());
  146.         FileUtils.writeFile("ACTIVATE_COMPANY_USER_ACCOUNT_"+companyId+"_"+DateScriptUtils.getStringDateForReportFileName(new Date()), stringBuilder.toString());
  147.         return null;
  148.     }
  149.  
  150.     private void activateUser(CompanyDTO company, UserCompanyAccountDTO userCompanyAccount, int i) throws AcquireLockException, MalformedURLException, RemoteException {
  151.         if (company != null &&
  152.                 userCompanyAccount != null) {
  153.             if (userCompanyAccount.getUserStatus() != UserStatusEnum.INVITED) {
  154.                 this.scriptLog("> User "+userCompanyAccount.getFullName()+" ("+company.getId()+"_"+userCompanyAccount.getId()+") status is not INVITED ("+userCompanyAccount.getUserStatus()+"), skipping user activation!");
  155.             } else if (userCompanyAccount.getUserOrigin() != UserOriginEnum.AD_IMPORT &&
  156.                         !isActivateNonADUsers) {
  157.                 this.scriptLog("> User "+userCompanyAccount.getFullName()+" ("+company.getId()+"_"+userCompanyAccount.getId()+") is not an AD user and will not be activated since the parameter activateNonADUsers is "+isActivateNonADUsers+"!");
  158.             } else {
  159.                 this.scriptLog("> Activating user "+userCompanyAccount.getFullName()+", "+userCompanyAccount.getEmailAddress()+" ("+company.getId()+"_"+userCompanyAccount.getId()+") - "+i+" of "+totalUsers);
  160.                 UserAccountDTO userAccount = userAccountUtil.getUserAccountById(userCompanyAccount.getId());
  161.                 if (userAccount == null) {
  162.                     this.scriptLog(">> Creating user account...");
  163.                     if (writeChanges) {
  164.                         userAccount = new UserAccountDTO();
  165.                         userAccount.setEmailAddress(userCompanyAccount.getEmailAddress());
  166.                         userAccount.setFirstName(userCompanyAccount.getFirstName());
  167.                         userAccount.setLastName(userCompanyAccount.getLastName());
  168.                         userAccount = this.userService.createUser(userAccount);
  169.                     }
  170.                 }
  171.                 if (userAccount != null) {
  172.                     this.scriptLog(">> Associating user company account to personal account...");
  173.                     if (writeChanges) {
  174.                         this.userService.associateUser(userAccount.getId(), userCompanyAccount.getId(), companyId);
  175.                         this.sendMail(company, userCompanyAccount);
  176.                     }
  177.                 } else {
  178.                     this.scriptLog(">> User not activated and email not sent. writeChanges:"+writeChanges+" | isSendMail:"+isSendMail);
  179.                 }
  180.             }
  181.         } else {
  182.             this.printNullCompanyOrUserError(company, userCompanyAccount);
  183.         }
  184.     }
  185.  
  186.     private void sendMail(CompanyDTO company, UserCompanyAccountDTO user) {
  187.         if (!writeChanges) {
  188.             this.scriptLog(">>> sendMail(): parameter writeChanges is "+writeChanges+", email won't be sent!");
  189.         } else {
  190.             if (isSendMail &&
  191.                     company != null &&
  192.                     user != null) {
  193.                 this.scriptLog(">>> sendMail(): parameter sendMail to " + user.getFullName() + " (" + user.getId() + ", " + user.getEmailAddress() + ") in company " + company.getItemName() + " (" + company.getId() + ") start...");
  194.                 String from = System.getProperty(ServerConstants.EMAIL_SERVER_ADMIN_EMAIL);
  195.                 try {
  196.                     EmailTemplateDTO emailTemplate = dbCompanyService.getEmailTemplate(company.getId(), EmailTemplateDTO.MailTypeEnum.AUTO_REGISTER, SupportedLocales.pt_BR.toString());
  197.                     emailTemplate.getMsgArgs().put(EmailTemplateDTO.MailTokenEnum.NAV_URL, "https://app.fluigidentity.com");
  198.                     Map<EmailTemplateDTO.MailTokenEnum, String> args = new EnumMap<>(EmailTemplateDTO.MailTokenEnum.class);
  199.                     if (emailTemplate != null) {
  200.                         URL url = new URL(emailTemplate.getMsgArgs().get(EmailTemplateDTO.MailTokenEnum.NAV_URL));
  201.                         String link = url.getProtocol() + "://" + company.getSubDomainName() + (url.getPort() != -1 ? ":" + url.getPort() : "");
  202.                         args.put(EmailTemplateDTO.MailTokenEnum.NAV_URL, link);
  203.                         args.put(EmailTemplateDTO.MailTokenEnum.COMPANY_NAME, company.getItemName());
  204.                         args.put(EmailTemplateDTO.MailTokenEnum.USER_FIRST_NAME, user.getFirstName());
  205.                         args.put(EmailTemplateDTO.MailTokenEnum.USER_LAST_NAME, user.getLastName());
  206.                         emailTemplate.setMsgArgs(args);
  207.                         emailTemplate.substituteArgsInMsg();
  208.                         String subject = emailTemplate.getSubject();
  209.                         String message = emailTemplate.getBody();
  210.                         InternetAddress[] internetAddress = new InternetAddress[1];
  211.                         internetAddress[0] = new InternetAddress(user.getEmailAddress());
  212.                         EmailInformation eInfo = new EmailInformation(internetAddress, subject, "UTF-8", message, "text/html; charset=UTF-8");
  213.                         Properties props = new Properties();
  214.                         props.clear();
  215.                         String emailTLS = System.getProperty(ServerConstants.EMAIL_SERVER_SMTP_TLS);
  216.                         props.put("mail.smtp.host", System.getProperty(ServerConstants.EMAIL_SERVER_SMTP_HOST));
  217.                         props.put("mail.smtp.port", System.getProperty(ServerConstants.EMAIL_SERVER_SMTP_PORT));
  218.                         props.put("mail.smtp.starttls.enable", (emailTLS != null ? emailTLS : "true"));
  219.                         props.put("mail.smtp.auth", true);
  220.                         String emailAdminUser = System.getProperty(ServerConstants.EMAIL_SERVER_ADMIN_NAME);
  221.                         String passwd = System.getProperty(ServerConstants.EMAIL_SERVER_ADMIN_PASSWORD);
  222.                         SMTPAuthenticator sAuth = new SMTPAuthenticator(emailAdminUser, passwd);
  223.                         Session session = Session.getInstance(props, sAuth);
  224.                         MimeMessage msg = new MimeMessage(session);
  225.                         msg.setFrom(new InternetAddress(from));
  226.                         msg.setRecipients(Message.RecipientType.TO, eInfo.getRecipients());
  227.                         msg.setSentDate(new Date(System.currentTimeMillis()));
  228.                         msg.setSubject(eInfo.getSubject(), eInfo.getSubjectType());
  229.                         msg.setContent(eInfo.getContent(), eInfo.getContentType());
  230.                         Transport.send(msg);
  231.                         this.scriptLog(">>> sendMail(): email sent: " + gson.toJson(msg));
  232.                     }
  233.                 } catch (Exception e) {
  234.                     this.scriptLog(">>> sendMail(): [EXCEPTION] " + e.getClass().getName() + " with this message: " + e.getMessage());
  235.                     e.printStackTrace();
  236.                 }
  237.             } else if (!isSendMail) {
  238.                 this.scriptLog(">>> sendMail(): parameter sendMail is " + isSendMail + ", email won't be sent!");
  239.             } else if (company == null ||
  240.                     user != null) {
  241.                 this.printNullCompanyOrUserError(company, user);
  242.             }
  243.         }
  244.     }
  245.  
  246.     private void scriptLog(String str) {
  247.         System.out.println(str);
  248.         stringBuilder.append(str).append(lineSeparator);
  249.     }
  250.  
  251.     private void printNullCompanyOrUserError(CompanyDTO company, UserCompanyAccountDTO userCompanyAccount) {
  252.         this.scriptLog("[ERROR] company and userCompanyAccount can't be null!");
  253.         if (company != null) {
  254.             this.scriptLog(" - company : "+company.toString());
  255.         } else {
  256.             this.scriptLog(" - company is null!");
  257.         }
  258.         if (userCompanyAccount != null) {
  259.             this.scriptLog(" - userCompanyAccount : "+userCompanyAccount.toString());
  260.         } else {
  261.             this.scriptLog(" - userCompanyAccount is null!");
  262.         }
  263.     }
  264.  
  265.     private void propertiesSetup() {
  266.         System.setProperty(ServerConstants.EMAIL_AGENTS_SIZE, "10");
  267.         System.setProperty(ServerConstants.EMAIL_AGENT_JOB_SIZE, "1000");
  268.         System.setProperty(ServerConstants.EMAIL_JOB_QUEUE_SIZE, "1000");
  269.         System.setProperty(ServerConstants.EMAIL_SERVER_SMTP_HOST, "email-smtp.us-east-1.amazonaws.com");
  270.         System.setProperty(ServerConstants.EMAIL_SERVER_SMTP_PORT, "587");
  271.         System.setProperty(ServerConstants.EMAIL_SERVER_SMTP_TLS, "true");
  272.         System.setProperty(ServerConstants.EMAIL_SERVER_ADMIN_PASSWORD, "AiGVhhfZtyFB2KZAgj1hQ6wbINOKfApwohmRhH7pAH3F");
  273.         System.setProperty(ServerConstants.EMAIL_SERVER_ADMIN_NAME, "AKIAJ2ES63Y36MDQTLYQ");
  274.         System.setProperty(ServerConstants.EMAIL_SERVER_ADMIN_EMAIL, "support@fluigidentity.com");
  275.     }
  276.  
  277.     class SMTPAuthenticator extends Authenticator {
  278.         private String user;
  279.         private String password;
  280.         public SMTPAuthenticator(String u, String p) {
  281.             this.user = u;
  282.             this.password = p;
  283.         }
  284.         public PasswordAuthentication getPasswordAuthentication() {
  285.             return new PasswordAuthentication(this.user, this.password);
  286.         }
  287.     }
  288. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement