AnsweredAssumed Answered

Envio Email Nuevo Usuario

Question asked by dfernandezgonzalez on May 13, 2011
Latest reply on Nov 16, 2016 by anky.p
Hola buenas,  aquí va el código para Enviar un Email con los datos de acceso a un nuevo usuario automáticamente. Espero que os sirva de algo. Seguramente hay algún fallo,y se podría mejorar, cualquier aporte será bienvenido.

Software necesario. Alfresco-community y alfresco-community-sdk tienen que coincidir en versión.

ALFRESCO http://process.alfresco.com/ccdl/?file=release/community/build-3370/alfresco-community-3.4.d-installer-linux-x64.bin.
ALFRESCO SDK  http://process.alfresco.com/ccdl/?file=release/community/build-3370/alfresco-community-sdk-3.4.d.zip

ALFRESCO MMT http://process.alfresco.com/ccdl/?file=release/community/build-2860/alfresco-mmt-3.3g.jar


Partiendo del alfresco-community-sdk BasicAmpSample, he modificado el código fuente.

build.xml

<?xml version="1.0" encoding="UTF-8"?>

<project name="New User Send Email" default="package-amp" basedir=".">
   
    <property name="project.dir" value="."/>
    <property name="build.dir" value="${project.dir}/build"/>
    <property name="config.dir" value="${project.dir}/config"/>
    <property name="jar.file" value="${build.dir}/lib/newuser-email.jar"/>
    <property name="amp.file" value="${build.dir}/dist/newuser-email.amp"/>
   
    <target name="mkdirs">
        <mkdir dir="${build.dir}/dist" />
        <mkdir dir="${build.dir}/lib" />
    </target>
   <target name="clean" description="removes all generated files">
         <delete dir="${build.dir}" />      
      </target>
    <path id="class.path">
        <dirset dir="${build.dir}" />
       <fileset dir="/alfresco-community-sdk-3.4.d/lib/server" includes="**/*.jar"/>
        <!– Tiene que indicar la ruta a esa carpeta dentro de alfresco-community-sdk-3.4.d –>
    </path>

    <target name="compile">
        <mkdir dir="${build.dir}/classes" />
        <javac classpathref="class.path" srcdir="${project.dir}/source/java" destdir="${build.dir}/classes" />
    </target>
   
    <target name="package-jar" depends="compile">
        <jar destfile="${jar.file}" >
            <fileset dir="${build.dir}/classes" excludes="**/custom*,**/*Test*" includes="**/*.class" />
        </jar>
    </target>
   
    <target name="package-amp" depends="mkdirs, package-jar" description="Package the Module" >
        <zip destfile="${amp.file}" >
            <fileset dir="${project.dir}/build" includes="lib/*.jar" />
            <fileset dir="${project.dir}" includes="config/**/*.*" excludes="**/module.properties" />
            <fileset dir="${project.dir}/config/alfresco/module/ampmodule" includes="module.properties" />
        </zip>
    </target>

    <target name="update-war" depends="package-amp" description="Update the WAR file.  Set -Dwar.file=…" >
        <echo>Installing New User Send Email AMP into WAR</echo>
        <java dir="." fork="true" classname="org.alfresco.repo.module.tool.ModuleManagementTool">
            <classpath refid="class.path" />
            <arg line="install ${amp.file} ${war.file} -force -verbose"/>
        </java>
    </target>

</project>

1) Dentro de carpeta config/

En el paquete alfresco.module.ampmodule

1.1)module-context.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN' 'http://www.springframework.org/dtd/spring-beans.dtd'>

<beans>
   
    <import resource="classpath:alfresco/module/ampmodule/context/service-context.xml" />
   
</beans>


1.2) module.properties


module.id=org.alfresco.module.ampmodule.SendEmail

module.title=Send Email New User
module.description=Envio de email con los datos de acceso al crear un nuevo usuario.
module.version=1.0

En el paquete alfresco.module.ampmodule.context

1.3) service-context.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC '-//SPRING//DTD BEAN//EN' 'http://www.springframework.org/dtd/spring-beans.dtd'>

<beans>
 
     <!– A simple class that is initialized by Spring –>
    <bean id="NewUserEmail" class="org.alfresco.module.ampmodule.NewUserEmail" init-method="init" >
       <property name="nodeService">   
         <ref bean="nodeService" />
      </property>
      <property name="policyComponent">
         <ref bean="policyComponent" />
      </property>
      <property name="serviceRegistry" ref="ServiceRegistry"/>
    </bean>
   
</beans>

En el paquete alfresco.module.ampmodule.template
1.4) new_user_email.ftl

<html>
<body>
<p>A new  Alfresco User has been created.</p>
<p>Hello, ${firstName}  ${lastName}</p>
<p>Your username is ${username} and your password is ${password} </p>

<p>${url.serverPath}${url.context}/faces/jsp/login.jsp</p>


<p>We strongly advise you to change your password when you log in for the first time.</p>

<p>Your Space Home is ${url.serverPath}${url.context}/navigate/browse/workspace/SpacesStore/${id} </p>


Regards
</body>
</html>



2)Dentro de la carpeta source/java

En el paquete org.alfresco.module.ampmodule

2.1)NewUserEmail.java


package org.alfresco.module.ampmodule;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.faces.context.FacesContext;
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.repository.datatype.DefaultTypeConverter;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.web.app.servlet.BaseTemplateContentServlet;
import org.alfresco.web.app.servlet.FacesHelper;
import org.apache.log4j.Logger;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;


/**
* Java class to send an email with access data to a new created user
*
*/
public class NewUserEmail implements NodeServicePolicies.OnCreateNodePolicy {

   /**
    * Log variable
    */
   private Logger logger = Logger.getLogger(NewUserEmail.class);
   

   /**
    * Policy Component for managing Policies and Behaviours
    */
   private PolicyComponent policyComponent;
   
   /**
    * NodeService for public and internal node and store operations.
    */
   private NodeService nodeService;
   
   /**
    * ServiceRegistry represents the registry of public Repository Services.
    * The registry provides meta-data about each service and provides access to the service interface.
    */
   private ServiceRegistry serviceRegistry;
   
   /**
    * User Home Directory
    */
   protected NodeRef homeFolder = null;
   
   /**
    * User Login
    */
   protected String userName = null;
   
   /**
    * User Password
    */
   protected String password = null;
   
   /**
    * User First Name
    */
   protected String firstName = null;
   
   /**
    * User Last Name
    */
    protected String lastName = null;
   
    /**
    * User Email
    */
   protected String email = null;
   
   /**
    * Email Subject
    */
   protected String subject = null;
   
   /**
    * Email Body
    */
   protected String body = null;
   
   /**
    * Email Template
    */
   private static final String NEW_USER_EMAIL_TEMPLATE = "alfresco/module/ampmodule/template/new_user_email.ftl";
   
   /**
    * Email From
    */
   private static final String EMAIL_FROM = "alfresco@gmail.com";
   
    /**
     *  Initialises the dialog bean
     */
   public void init()
    {

      this.email = "";
      this.userName = "";
      this.password = "";
      this.firstName = "";
        this.lastName = "";
      this.subject = "New User Alfresco";
      this.body = "";
      
      /**
       * Associate the behavior of the class. When you create a user calls the method notificarUsuario
       */
      this.policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI,"onCreateNode"), ContentModel.TYPE_PERSON, new JavaBehaviour(this,"notificarUsuario", org.alfresco.repo.policy.JavaBehaviour.NotificationFrequency.TRANSACTION_COMMIT));                         
      
    }
   
   /**
    * Called when a new node has been created.
    */
   public void onCreateNode(ChildAssociationRef childAssocRef)
   {
      if (logger.isInfoEnabled()) logger.info(" NewUserEmail Node create policy fired");
   }
   
   /**
    * Set the node service
    *
    * @param nodeService the node service
    */
   public void setNodeService(NodeService nodeService)
   {
      this.nodeService = nodeService;
   }

   /**
    * Set the policy component
    *
    * @param policyComponent the policy component
    */
   public void setPolicyComponent(PolicyComponent policyComponent) {   
      this.policyComponent = policyComponent;
    }
   
   /**
     * Set the service registry
     *
     * @param serviceRegistry   the service registry
     */
     public void setServiceRegistry(ServiceRegistry serviceRegistry) {
           this.serviceRegistry = serviceRegistry;
    }
   
   /**
    * Get email subject
    * @return email subject.
    */
   public String getSubject()
   {
      return this.subject;
   }
   
   /**
    *  Get email body
    * @return email body.
    */
   public String getBody()
   {
      return this.body;
   }
   
   /**
    *  Get user email
    * @return user email.
    */
   public String getEmail()
   {
      return this.email;
   }

   /**
    * Get user login
    * @return user login .
    */
   public String getUserName()
   {
      return this.userName;
   }

   /**
    * Get user first name
    * @return user first name.
    */
   public String getFirstName()
   {
      return this.firstName;
   }

   /**
    * Get user last name
    * @return user last name.
    */
   public String getLastName()
   {
      return this.lastName;
   }
   
   /**
    * Get user password
    * @return user password
    */
   public String getPassword() {
      return password;
   }

   /**
    * Set user password
    * @param password user password
    */
   public void setPassword(String password) {
      this.password = password;
   }
   
   /**
    * get user home folder
    * @return user home folder
    */
   public NodeRef getHomeFolder() {
      return homeFolder;
   }

   /**
    *  Retrieves user data from a node and call sendEmail() function
    * @param childAssocRef the primary parent-child association of the created node
    */
   public void notificarUsuario(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);
      this.firstName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_FIRSTNAME);
      this.lastName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_LASTNAME);
      this.homeFolder = DefaultTypeConverter.INSTANCE.convert(NodeRef.class, nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER));
      sendEmail();
   }
   
 

   /**
    * Build Email and call send() function
    * @throws AlfrescoRuntimeException If template isn't found, email is constructed "manually"
    */
   public void sendEmail() throws AlfrescoRuntimeException 
    {
      
      Map<String, Object> model = new HashMap<String, Object>();
      
      if (getEmail() != null &&  getEmail() != "")
      {
         // Search user by email
         Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL,getEmail());
         
          if (result.size() == 1)
          {
               // Generate a random password for the user
                cambiarPassword(getUserName());
                // Get application url
                FacesContext fc = FacesContext.getCurrentInstance();
               BaseTemplateContentServlet.URLHelper url =  new BaseTemplateContentServlet.URLHelper(fc);
               
               ClasspathScriptLocation location = new ClasspathScriptLocation(NEW_USER_EMAIL_TEMPLATE);
               
               try
               {
                  if(location.getInputStream() != null) // Check that there is a template
                  {
                     // build the email template model
                     model.put("username", getUserName());
                     model.put("firstName", getFirstName());
                     model.put("lastName", getLastName());
                     model.put("id",getHomeFolder().getId());
                     model.put("url",url );   
                     model.put("password",getPassword());
                     
                     this.body =   serviceRegistry.getTemplateService().processTemplate("freemarker", NEW_USER_EMAIL_TEMPLATE, model);
                     send();
                  }
                  
               }
               catch(AlfrescoRuntimeException e) // If template isn't found, email is constructed "manually"
               {
                  logger.error("Email Template no encontrado " + NEW_USER_EMAIL_TEMPLATE );
                  
                  this.body = "<html>   <body> <p> A new  Alfresco User has been created.</p>" +
                  "<p>Hello, " +getFirstName() +" "+ getLastName()+ " </p><p>Your username is " +getUserName() + " and your " +
                  "passowrd is " + getPassword() + "</p> " +
                  "<p>" +url.getServerPath() + url.getContext() + "/faces/jsp/login.jsp</p>" +
                  "<p>We strongly advise you to change your password when you log in for the first time.</p>" +
                  "<p>Your Space Home is" + url.getServerPath() + url.getContext() +
                  "/navigate/browse/workspace/SpacesStore/" +getHomeFolder().getId() +  "</p>" +
                  "Regards</body>   </html>";
                  send();
               }
         }
      }

    }
   
   
   /**
    * Java function to send email
    */
   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);
          }
      };
      // Send the message
      this.getMailSender().send(mailPreparer);
   }

   /**
    * Get mail sender
    * @return JavaMailSender
    */
   protected JavaMailSender getMailSender() {
      JavaMailSender mailSender = null;
      if (mailSender == null) {
          mailSender = (JavaMailSender) FacesHelper.getManagedBean(FacesContext.getCurrentInstance(), "mailService");
      }
      return mailSender;
   }
   
   /**
    *
    * Generates a random password, and saves the information
    * @param userName user that the password is changed
    */
   public void cambiarPassword(String userName)
   {
      //Set the system user as the currently running user for authentication purposes.
      AuthenticationUtil.setRunAsUserSystem();
      //Check that the person exists by email
      Set<NodeRef> result = serviceRegistry.getPersonService().getPeopleFilteredByProperty(ContentModel.PROP_EMAIL,getEmail());
      
      if (result.size() == 1)
      {
      
         Object[] userNodeRefs = result.toArray();
         eNodeRef userNodeRef = (NodeRef) userNodeRefs[0];
          
         
         String username = (String) serviceRegistry.getNodeService().getProperty(userNodeRef,ContentModel.PROP_USERNAME);
         // Generate random password
         String nuevoPassword = Password.generarPassword();
               
         char[] cadenaChars = new char[nuevoPassword.length()];
          
         for (int i=0; i<nuevoPassword.length(); i++)
         {
            cadenaChars[i] = nuevoPassword.charAt(i);
         }
         // Save new password
         serviceRegistry.getAuthenticationService().setAuthentication(username, nuevoPassword.toCharArray());
         // Save new password
          setPassword(nuevoPassword);
        
      }
     
   }

   
}

2.2) Password.java


package org.alfresco.module.ampmodule;

/**
* Java class that generates a random password of 8 characters
*
*/
public class Password
{
   /**
    * Password length
    */
   private static final int  length = 8;
   
   /**
    * Numbers that can be part of a generated password
    */
   private static final String NUMEROS = "0123456789";
   
   /**
    * Capital letters that can be part of a generated password
    */
   private static final String MAYUSCULAS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   
   /**
    * Lowercase letters that can be part of a generated password
    */
   private static final String MINUSCULAS = "abcdefghijklmnopqrstuvwxyz";
   
   /**
    * Generate a random password
    * @return random password
    */
   public static String generarPassword() {
      String key = NUMEROS + MAYUSCULAS + MINUSCULAS;
      String pswd = "";

      for (int i = 0; i < length; i++) {
         pswd+=(key.charAt((int)(Math.random() * key.length())));
      }

      return pswd;
   }
   
}


Una vez terminado, nos situamos en el directorio base del proyecto y ejecutamos.


ant

Despues ejecutamos, teniendo en cuenta que las direcciones relativas a los archivos  alfresco-mmt-3.3g.jar  y alfresco.war
Para más opciones http://wiki.alfresco.com/wiki/Module_Management_Tool


java -jar alfresco-mmt-3.3g.jar install build/dist/newuser-email.amp alfresco.war -verbose


Ahora ya tenemos nuestro nuevo módulo dentro del archivo war, con lo que lo copiamos en el directorio $TOMCAT_HOME/webapps y arrancamos tomcat.

Outcomes