11-16-2016 01:33 AM
I have created a class NewUserEmail.java to auto generate an email with username and password while creating a new user. I am able to create the password but whenever I am trying to log in with that password, its not logging in. I am not able to generate my mail. Please guide me and let me know what is wrong with my code:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.jscript.ClasspathScriptLocation;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {
private Logger logger = Logger.getLogger(NewUserEmail.class);
private PolicyComponent policyComponent;
private NodeService nodeService;
private PersonService personService;
private ServiceRegistry serviceRegistry;
protected String userName = null;
protected String password = null;
protected String email = null;
protected String subject = null;
protected String body = null;
private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/demoact1-repo/template/new_user_email.ftl";
private static final String EMAIL_FROM = "no-reply@eisenvault.com";
public void init()
{
this.email = "";
this.userName = "";
this.password = "";
this.subject = "New User Alfresco";
this.body = "";
this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI,"onCreateNode"), ContentModel.TYPE_PERSON, new JavaBehaviour(this,"ReportUser", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT));
}
public void onCreateNode(ChildAssociationRef childAssocRef)
{
if (logger.isInfoEnabled()) logger.info(" NewUserEmail Node create policy fired");
}
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
public String getSubject()
{
return this.subject;
}
public String getBody()
{
return this.body;
}
public String getEmail()
{
return this.email;
}
public String getUserName()
{
return this.userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void ReportUser(ChildAssociationRef childAssocRef)
{
NodeRef personRef = childAssocRef.getChildRef();
this.userName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
this.email = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_EMAIL);
sendEmail();
}
public void sendEmail() throws AlfrescoRuntimeException
{
Map<String, Object> templateModel = new HashMap<String, Object>();
if (getEmail() != null && getEmail() != "")
{
Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL,getEmail(),1);
if (result.size() == 1)
{
changePassword(getUserName());
ClasspathScriptLocation location = new ClasspathScriptLocation(NEW_USER_EMAIL_TEMPLATE);
try
{
if(location.getInputStream() != null) // Check that there is a template
{
templateModel.put("userName", getUserName());
templateModel.put("password",getPassword());
this.body = serviceRegistry.getTemplateService().processTemplate("freemarker", NEW_USER_EMAIL_TEMPLATE, templateModel);
}
}
catch(AlfrescoRuntimeException e) // If template isn't found, email is constructed "manually"
{
logger.error("Email Template not found " + NEW_USER_EMAIL_TEMPLATE );
this.body = "<html> <body> <p> A new User has been created.</p>" +
"<p>Hello, </p><p>Your username is " +getUserName() + " and your " +
"password is " + getPassword() + "</p> " +
"<p>We strongly advise you to change your password when you log in for the first time.</p>" +
"Regards</body> </html>";
//send();
}
}
}
}
protected void send()
{
MimeMessagePreparator mailPreparer = new MimeMessagePreparator()
{
public void prepare(MimeMessage mimeMessage) throws MessagingException
{
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setTo(getEmail());
message.setSubject(getSubject());
message.setText(getBody(),true);
message.setFrom(EMAIL_FROM);
}
};
}
public void changePassword(String password)
{
AuthenticationUtil.setRunAsUserSystem();
Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL,getEmail(),1);
if (result.size() == 1)
{
Object[] userNodeRefs = result.toArray();
NodeRef userNodeRef = (NodeRef) userNodeRefs[0];
String username = (String) serviceRegistry.getNodeService().getProperty(userNodeRef,ContentModel.PROP_USERNAME);
// Generate random password
String newPassword = Password.generatePassword();
char[] cadChars = new char[newPassword.length()];
for (int i=0; i<newPassword.length(); i++)
{
cadChars[i] = newPassword.charAt(i);
}
serviceRegistry.getAuthenticationService().setAuthentication(username, newPassword.toCharArray());
setPassword(newPassword);
System.out.println("Password is :" + newPassword);
}
}
}
11-17-2016 02:59 AM
Got the answer:
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.executer.MailActionExecuter;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {
private Logger logger = Logger.getLogger(NewUserEmail.class);
private PolicyComponent policyComponent;
private NodeService nodeService;
private ServiceRegistry serviceRegistry;
private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/demoact1-repo/template/new_user_email.ftl";
private static final String EMAIL_FROM = "no-reply@eisenvault.com";
private static final String EMAIL_SUBJECT = "New User Alfresco";
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
public void init() {
this.policyComponent.bindClassBehaviour(
QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateNode"),
ContentModel.TYPE_PERSON,
new JavaBehaviour(this, "ReportUser", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT)
);
}
public void onCreateNode(ChildAssociationRef childAssocRef) {
reportUser(childAssocRef);
}
private void reportUser(ChildAssociationRef childAssocRef) {
NodeRef personRef = childAssocRef.getChildRef();
String username = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
if (StringUtils.isEmpty(username)) {
throw new AlfrescoRuntimeException("Cannot get username, ref: " + childAssocRef);
}
String email = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_EMAIL);
if (StringUtils.isEmpty(email)) {
throw new AlfrescoRuntimeException("Cannot get email, username: " + username + ", ref: " + childAssocRef);
}
String newPassword = generateRandomPassword();
changePassword(username, newPassword);
sendEmail(username, newPassword, email);
}
private void sendEmail(String username, String newPassword, String recipient) {
ActionService actionService = serviceRegistry.getActionService();
Action ma = actionService.createAction(MailActionExecuter.NAME);
ma.setParameterValue(MailActionExecuter.PARAM_SUBJECT, EMAIL_SUBJECT);
ma.setParameterValue(MailActionExecuter.PARAM_FROM, EMAIL_FROM);
ma.setParameterValue(MailActionExecuter.PARAM_TO, recipient);
ma.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, NEW_USER_EMAIL_TEMPLATE);
Map<String, Serializable> templateModel = new HashMap<>();
templateModel.put("userName", username);
templateModel.put("password", newPassword);
ma.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) templateModel);
actionService.executeAction(ma, null);
}
private void changePassword(final String username, final String newPassword) {
// run this as an Admin user, he can change password without knowing the original one!
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() {
public Void doWork() throws Exception {
serviceRegistry.getAuthenticationService().setAuthentication(username, newPassword.toCharArray());
logger.info("User '" + username + "' password has been changed");
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
private String generateRandomPassword() {
return UUID.randomUUID().toString();
//or return new BigInteger(130, new SecureRandom()).toString(32);
}
}
11-16-2016 01:55 AM
have you tried to use org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.TRANSACTION_COMMIT instead of org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT
11-16-2016 02:01 AM
Yes earlier I did that was not able to create user from UI. So changed to EVERY_EVENT.
11-16-2016 03:47 AM
I think maybe you should execute your code atfer the transaction event commit
You can refer to https://joinup.ec.europa.eu/svn/circabc/SDK%20Circa/source/java/eu/cec/digit/circabc/aspect/ContentN...
11-16-2016 06:04 AM
Tried...not working
11-17-2016 02:59 AM
Got the answer:
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.action.executer.MailActionExecuter;
import org.alfresco.repo.node.NodeServicePolicies;
import org.alfresco.repo.policy.JavaBehaviour;
import org.alfresco.repo.policy.PolicyComponent;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.action.Action;
import org.alfresco.service.cmr.action.ActionService;
import org.alfresco.service.cmr.repository.ChildAssociationRef;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {
private Logger logger = Logger.getLogger(NewUserEmail.class);
private PolicyComponent policyComponent;
private NodeService nodeService;
private ServiceRegistry serviceRegistry;
private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/demoact1-repo/template/new_user_email.ftl";
private static final String EMAIL_FROM = "no-reply@eisenvault.com";
private static final String EMAIL_SUBJECT = "New User Alfresco";
public void setNodeService(NodeService nodeService) {
this.nodeService = nodeService;
}
public void setPolicyComponent(PolicyComponent policyComponent) {
this.policyComponent = policyComponent;
}
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
public void init() {
this.policyComponent.bindClassBehaviour(
QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateNode"),
ContentModel.TYPE_PERSON,
new JavaBehaviour(this, "ReportUser", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.EVERY_EVENT)
);
}
public void onCreateNode(ChildAssociationRef childAssocRef) {
reportUser(childAssocRef);
}
private void reportUser(ChildAssociationRef childAssocRef) {
NodeRef personRef = childAssocRef.getChildRef();
String username = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
if (StringUtils.isEmpty(username)) {
throw new AlfrescoRuntimeException("Cannot get username, ref: " + childAssocRef);
}
String email = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_EMAIL);
if (StringUtils.isEmpty(email)) {
throw new AlfrescoRuntimeException("Cannot get email, username: " + username + ", ref: " + childAssocRef);
}
String newPassword = generateRandomPassword();
changePassword(username, newPassword);
sendEmail(username, newPassword, email);
}
private void sendEmail(String username, String newPassword, String recipient) {
ActionService actionService = serviceRegistry.getActionService();
Action ma = actionService.createAction(MailActionExecuter.NAME);
ma.setParameterValue(MailActionExecuter.PARAM_SUBJECT, EMAIL_SUBJECT);
ma.setParameterValue(MailActionExecuter.PARAM_FROM, EMAIL_FROM);
ma.setParameterValue(MailActionExecuter.PARAM_TO, recipient);
ma.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, NEW_USER_EMAIL_TEMPLATE);
Map<String, Serializable> templateModel = new HashMap<>();
templateModel.put("userName", username);
templateModel.put("password", newPassword);
ma.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, (Serializable) templateModel);
actionService.executeAction(ma, null);
}
private void changePassword(final String username, final String newPassword) {
// run this as an Admin user, he can change password without knowing the original one!
AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Void>() {
public Void doWork() throws Exception {
serviceRegistry.getAuthenticationService().setAuthentication(username, newPassword.toCharArray());
logger.info("User '" + username + "' password has been changed");
return null;
}
}, AuthenticationUtil.getSystemUserName());
}
private String generateRandomPassword() {
return UUID.randomUUID().toString();
//or return new BigInteger(130, new SecureRandom()).toString(32);
}
}
Tags
Find what you came for
We want to make your experience in Hyland Connect as valuable as possible, so we put together some helpful links.