Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.fluig.identity.scripts.impl;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.rmi.RemoteException;
- import java.util.Date;
- import java.util.EnumMap;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Properties;
- import javax.mail.Authenticator;
- import javax.mail.Message;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import org.apache.commons.lang.StringUtils;
- import com.beust.jcommander.Parameter;
- import com.beust.jcommander.Parameters;
- import com.beust.jcommander.ParametersDelegate;
- import com.fluig.identity.ScriptInterface;
- import com.fluig.identity.scripts.utils.DateScriptUtils;
- import com.fluig.identity.scripts.utils.UserAccount;
- import com.fluig.identity.util.FileLoggerUtil;
- import com.fluig.identity.util.FileUtils;
- import com.totvslabs.idm.common.model.CompanyDTO;
- import com.totvslabs.idm.common.model.EmailTemplateDTO;
- import com.totvslabs.idm.common.model.UserAccountDTO;
- import com.totvslabs.idm.common.model.UserCompanyAccountDTO;
- import com.totvslabs.idm.common.model.UserLiteDTO;
- import com.totvslabs.idm.common.util.DateFormatUtils;
- import com.totvslabs.idm.common.util.SupportedLocales;
- import com.totvslabs.idm.common.util.UserOriginEnum;
- import com.fluig.identity.core.enums.UserStatusEnum;
- import com.totvslabs.idm.core.email.EmailInformation;
- import com.totvslabs.idm.db.dbInterface.DBCompanyService;
- import com.totvslabs.idm.db.exception.AcquireLockException;
- import com.totvslabs.idm.db.services.DBCompanyServiceImpl;
- import com.totvslabs.idm.db.services.DBUserServiceImpl;
- import com.totvslabs.idm.utils.ServerConstants;
- /**
- * Created by tiago.jensen on 09/02/2017.
- */
- @Parameters(commandNames = {"activateAllCompanyUsers"}, commandDescription = "Activate all company users")
- public class ActivateAllCompanyUsersScript extends ScriptInterface {
- public static final ActivateAllCompanyUsersScript instance = new ActivateAllCompanyUsersScript();
- private final DBUserServiceImpl userService = new DBUserServiceImpl();
- private final DBCompanyService dbCompanyService = new DBCompanyServiceImpl();
- int totalUsers = 0;
- StringBuilder stringBuilder = new StringBuilder();
- String lineSeparator = System.lineSeparator();
- @ParametersDelegate
- protected UserAccount userAccountUtil = new UserAccount(bucket);
- @Parameter(names = {"--companyId", "-C"}, description = "Company ID", required = true)
- protected String companyId;
- @Parameter(names = {"--userId", "-U"}, description = "User ID")
- protected String userId = null;
- @Parameter(names = {"--activateNonADUsers", "-A"}, description = "Activate Non AD Users (yes or y to activate)")
- protected String activateNonADUsers = "no";
- protected boolean isActivateNonADUsers = false;
- @Parameter(names = {"--sendMail", "-M"}, description = "Activated user should receive notification mail (yes or y to send mail)")
- protected String sendMail = "no";
- protected boolean isSendMail = false;
- @Parameter(names = {"--to", "-T"}, description = "Email address to send test")
- protected String to;
- @Override
- public Object call() throws Exception {
- this.scriptLog(FileLoggerUtil.TOPIC_SPACER);
- this.scriptLog("Executing ActivateAllCompanyUsersScript...");
- this.scriptLog("Params");
- this.scriptLog(" writeChanges: "+writeChanges);
- this.scriptLog(" companyId: "+companyId);
- this.scriptLog(" userId: "+userId);
- this.scriptLog(" activateNonADUsers: "+activateNonADUsers);
- this.scriptLog(" sendMail: "+sendMail);
- this.scriptLog(" to: "+to);
- this.scriptLog("Date: "+ DateFormatUtils.getStringDateBR(new Date()));
- this.scriptLog(FileLoggerUtil.TOPIC_SPACER);
- propertiesSetup();
- if ("yes".equalsIgnoreCase(activateNonADUsers) ||
- "y".equalsIgnoreCase(activateNonADUsers)) {
- isActivateNonADUsers = true;
- }
- if ("yes".equalsIgnoreCase(sendMail) ||
- "y".equalsIgnoreCase(sendMail)) {
- isSendMail = true;
- }
- UserCompanyAccountDTO userCompanyAccountDTO;
- CompanyDTO companyDTO = dbCompanyService.getCompany(companyId);
- if (companyDTO == null) {
- this.scriptLog("[ERROR] COMPANY NOT FOUND!!!");
- return null;
- }
- if (StringUtils.isNotBlank(to)) {
- UserCompanyAccountDTO tempUser = new UserCompanyAccountDTO();
- tempUser.setEmailAddress(to);
- tempUser.setFirstName("Test");
- tempUser.setFirstName("Sendmail");
- this.sendMail(companyDTO, tempUser);
- return null;
- }
- if (userId != null) {
- userCompanyAccountDTO = userAccountUtil.getUserCompanyAccountById(userId, companyId);
- if (userCompanyAccountDTO != null) {
- this.activateUser(companyDTO, userCompanyAccountDTO, 1);
- } else {
- this.scriptLog("[ERROR] USER COMPANY ACCOUNT NOT FOUND! ("+companyId+"_"+userId+")");
- }
- } else {
- HashMap<String, UserLiteDTO> allCompanyUserAccounts = userAccountUtil.getAllCompanyUserAccounts(companyId);
- if (allCompanyUserAccounts != null &&
- !allCompanyUserAccounts.isEmpty()) {
- int i = 0;
- this.totalUsers = allCompanyUserAccounts.size();
- for (String key : allCompanyUserAccounts.keySet()) {
- i++;
- userCompanyAccountDTO = userAccountUtil.getUserCompanyAccountById(key, companyId);
- if (userCompanyAccountDTO != null) {
- this.activateUser(companyDTO, userCompanyAccountDTO, i);
- } else {
- this.scriptLog("[ERROR] USER COMPANY ACCOUNT NOT FOUND! ("+companyId+"_"+key+")");
- }
- this.scriptLog(FileLoggerUtil.LINE_SPACER);
- }
- } else {
- this.scriptLog("[ERROR] USER COMPANY ACCOUNT LIST NOT FOUND! ("+companyId+")");
- }
- }
- this.scriptLog(FileLoggerUtil.TOPIC_SPACER);
- System.out.println(stringBuilder.toString());
- FileUtils.writeFile("ACTIVATE_COMPANY_USER_ACCOUNT_"+companyId+"_"+DateScriptUtils.getStringDateForReportFileName(new Date()), stringBuilder.toString());
- return null;
- }
- private void activateUser(CompanyDTO company, UserCompanyAccountDTO userCompanyAccount, int i) throws AcquireLockException, MalformedURLException, RemoteException {
- if (company != null &&
- userCompanyAccount != null) {
- if (userCompanyAccount.getUserStatus() != UserStatusEnum.INVITED) {
- this.scriptLog("> User "+userCompanyAccount.getFullName()+" ("+company.getId()+"_"+userCompanyAccount.getId()+") status is not INVITED ("+userCompanyAccount.getUserStatus()+"), skipping user activation!");
- } else if (userCompanyAccount.getUserOrigin() != UserOriginEnum.AD_IMPORT &&
- !isActivateNonADUsers) {
- 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+"!");
- } else {
- this.scriptLog("> Activating user "+userCompanyAccount.getFullName()+", "+userCompanyAccount.getEmailAddress()+" ("+company.getId()+"_"+userCompanyAccount.getId()+") - "+i+" of "+totalUsers);
- UserAccountDTO userAccount = userAccountUtil.getUserAccountById(userCompanyAccount.getId());
- if (userAccount == null) {
- this.scriptLog(">> Creating user account...");
- if (writeChanges) {
- userAccount = new UserAccountDTO();
- userAccount.setEmailAddress(userCompanyAccount.getEmailAddress());
- userAccount.setFirstName(userCompanyAccount.getFirstName());
- userAccount.setLastName(userCompanyAccount.getLastName());
- userAccount = this.userService.createUser(userAccount);
- }
- }
- if (userAccount != null) {
- this.scriptLog(">> Associating user company account to personal account...");
- if (writeChanges) {
- this.userService.associateUser(userAccount.getId(), userCompanyAccount.getId(), companyId);
- this.sendMail(company, userCompanyAccount);
- }
- } else {
- this.scriptLog(">> User not activated and email not sent. writeChanges:"+writeChanges+" | isSendMail:"+isSendMail);
- }
- }
- } else {
- this.printNullCompanyOrUserError(company, userCompanyAccount);
- }
- }
- private void sendMail(CompanyDTO company, UserCompanyAccountDTO user) {
- if (!writeChanges) {
- this.scriptLog(">>> sendMail(): parameter writeChanges is "+writeChanges+", email won't be sent!");
- } else {
- if (isSendMail &&
- company != null &&
- user != null) {
- this.scriptLog(">>> sendMail(): parameter sendMail to " + user.getFullName() + " (" + user.getId() + ", " + user.getEmailAddress() + ") in company " + company.getItemName() + " (" + company.getId() + ") start...");
- String from = System.getProperty(ServerConstants.EMAIL_SERVER_ADMIN_EMAIL);
- try {
- EmailTemplateDTO emailTemplate = dbCompanyService.getEmailTemplate(company.getId(), EmailTemplateDTO.MailTypeEnum.AUTO_REGISTER, SupportedLocales.pt_BR.toString());
- emailTemplate.getMsgArgs().put(EmailTemplateDTO.MailTokenEnum.NAV_URL, "https://app.fluigidentity.com");
- Map<EmailTemplateDTO.MailTokenEnum, String> args = new EnumMap<>(EmailTemplateDTO.MailTokenEnum.class);
- if (emailTemplate != null) {
- URL url = new URL(emailTemplate.getMsgArgs().get(EmailTemplateDTO.MailTokenEnum.NAV_URL));
- String link = url.getProtocol() + "://" + company.getSubDomainName() + (url.getPort() != -1 ? ":" + url.getPort() : "");
- args.put(EmailTemplateDTO.MailTokenEnum.NAV_URL, link);
- args.put(EmailTemplateDTO.MailTokenEnum.COMPANY_NAME, company.getItemName());
- args.put(EmailTemplateDTO.MailTokenEnum.USER_FIRST_NAME, user.getFirstName());
- args.put(EmailTemplateDTO.MailTokenEnum.USER_LAST_NAME, user.getLastName());
- emailTemplate.setMsgArgs(args);
- emailTemplate.substituteArgsInMsg();
- String subject = emailTemplate.getSubject();
- String message = emailTemplate.getBody();
- InternetAddress[] internetAddress = new InternetAddress[1];
- internetAddress[0] = new InternetAddress(user.getEmailAddress());
- EmailInformation eInfo = new EmailInformation(internetAddress, subject, "UTF-8", message, "text/html; charset=UTF-8");
- Properties props = new Properties();
- props.clear();
- String emailTLS = System.getProperty(ServerConstants.EMAIL_SERVER_SMTP_TLS);
- props.put("mail.smtp.host", System.getProperty(ServerConstants.EMAIL_SERVER_SMTP_HOST));
- props.put("mail.smtp.port", System.getProperty(ServerConstants.EMAIL_SERVER_SMTP_PORT));
- props.put("mail.smtp.starttls.enable", (emailTLS != null ? emailTLS : "true"));
- props.put("mail.smtp.auth", true);
- String emailAdminUser = System.getProperty(ServerConstants.EMAIL_SERVER_ADMIN_NAME);
- String passwd = System.getProperty(ServerConstants.EMAIL_SERVER_ADMIN_PASSWORD);
- SMTPAuthenticator sAuth = new SMTPAuthenticator(emailAdminUser, passwd);
- Session session = Session.getInstance(props, sAuth);
- MimeMessage msg = new MimeMessage(session);
- msg.setFrom(new InternetAddress(from));
- msg.setRecipients(Message.RecipientType.TO, eInfo.getRecipients());
- msg.setSentDate(new Date(System.currentTimeMillis()));
- msg.setSubject(eInfo.getSubject(), eInfo.getSubjectType());
- msg.setContent(eInfo.getContent(), eInfo.getContentType());
- Transport.send(msg);
- this.scriptLog(">>> sendMail(): email sent: " + gson.toJson(msg));
- }
- } catch (Exception e) {
- this.scriptLog(">>> sendMail(): [EXCEPTION] " + e.getClass().getName() + " with this message: " + e.getMessage());
- e.printStackTrace();
- }
- } else if (!isSendMail) {
- this.scriptLog(">>> sendMail(): parameter sendMail is " + isSendMail + ", email won't be sent!");
- } else if (company == null ||
- user != null) {
- this.printNullCompanyOrUserError(company, user);
- }
- }
- }
- private void scriptLog(String str) {
- System.out.println(str);
- stringBuilder.append(str).append(lineSeparator);
- }
- private void printNullCompanyOrUserError(CompanyDTO company, UserCompanyAccountDTO userCompanyAccount) {
- this.scriptLog("[ERROR] company and userCompanyAccount can't be null!");
- if (company != null) {
- this.scriptLog(" - company : "+company.toString());
- } else {
- this.scriptLog(" - company is null!");
- }
- if (userCompanyAccount != null) {
- this.scriptLog(" - userCompanyAccount : "+userCompanyAccount.toString());
- } else {
- this.scriptLog(" - userCompanyAccount is null!");
- }
- }
- private void propertiesSetup() {
- System.setProperty(ServerConstants.EMAIL_AGENTS_SIZE, "10");
- System.setProperty(ServerConstants.EMAIL_AGENT_JOB_SIZE, "1000");
- System.setProperty(ServerConstants.EMAIL_JOB_QUEUE_SIZE, "1000");
- System.setProperty(ServerConstants.EMAIL_SERVER_SMTP_HOST, "email-smtp.us-east-1.amazonaws.com");
- System.setProperty(ServerConstants.EMAIL_SERVER_SMTP_PORT, "587");
- System.setProperty(ServerConstants.EMAIL_SERVER_SMTP_TLS, "true");
- System.setProperty(ServerConstants.EMAIL_SERVER_ADMIN_PASSWORD, "AiGVhhfZtyFB2KZAgj1hQ6wbINOKfApwohmRhH7pAH3F");
- System.setProperty(ServerConstants.EMAIL_SERVER_ADMIN_NAME, "AKIAJ2ES63Y36MDQTLYQ");
- System.setProperty(ServerConstants.EMAIL_SERVER_ADMIN_EMAIL, "support@fluigidentity.com");
- }
- class SMTPAuthenticator extends Authenticator {
- private String user;
- private String password;
- public SMTPAuthenticator(String u, String p) {
- this.user = u;
- this.password = p;
- }
- public PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(this.user, this.password);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement