Calling Component in a servlet | Community
Skip to main content
August 23, 2017
Solved

Calling Component in a servlet

  • August 23, 2017
  • 8 replies
  • 7246 views

I have a query regarding the email flow. I have implemented email servlet which receives request from client side in a POST call. Once received I call the EmailService component in the servlet. This component should get configuration details from OSGi (server,port,username,password) and from,to,subject,message details from client side and send the email using javax mail jar. However, the configuration from OSGi is not successful.

I want to understand how to call component (gathers configuration from OSGi) from servlet.

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by viveksachdeva

mallikac49331008 You should not instantiate service object

like:EmailService mailService = new EmailServiceImpl();

You already have reference to it as emailService. Just use that to call send mail method.

Moreover, you dont seem to have set the default values of the properties. You can ser values using http://www.aemcq5tutorials.com/tutorials/custom-osgi-configuration-aem/ or by creating a config node corresponding to the component pid.

https://www.youtube.com/watch?v=FF8wWILATMM

8 replies

August 23, 2017

Below is my java code snippet for Email servlet

@SlingServlet(paths="/bin/sendEmail", methods = "POST", metatype=true)

public class EmailServlet extends org.apache.sling.api.servlets.SlingAllMethodsServlet {

  private static final Logger LOG = LoggerFactory.getLogger(EmailServlet.class);

  @Reference

    private SlingRepository repository;

  

    public void bindRepository(SlingRepository repository) {

           this.repository = repository;

           }

 

    @Reference

    private transient EmailService emailService;

 

    @Override

    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {

   

     try

     {

        //Get the submitted form data that is sent from the

             //CQ web page

      

         String subject = request.getParameter("subject");

         String message = request.getParameter("message");

         String toEmail = request.getParameter("toAddress");

         String fromEmail = request.getParameter("fromAddress");

               

         EmailService mailService = new EmailServiceImpl();

      

         LOG.info("before calling send email method:");

         mailService.send(toEmail,fromEmail,subject,message,null); // Calling the component

         LOG.info("after calling send email method:");

            //Get the JSON formatted data 

      

       

            //Return the JSON formatted data

        //response.getWriter().write(jsonData);

     }

     catch(Exception e)

     {

         e.printStackTrace();

     }

   }

}

Below is my java code snippet for Email service component

@Component(metatype=true,immediate = true, enabled=true, label = "Email Service Info")

@Service(value = {EmailService.class})

public class EmailServiceImpl implements EmailService{

  private static final Logger LOG = LoggerFactory.getLogger(EmailServiceImpl.class);

  @Reference

  private ResourceResolverFactory resolverFactory;

  //private final Logger logger = LoggerFactory.getLogger(getClass());

  @Property(label = "Smtp server", description="Smtp server info")

  public static final String SMTP_SERVER = "server";

  @Property(label="port", description = "Smtp port")

  public static final String SMTP_PORT = "port";

  @Property(label="username", description = "username")

  public static final String EMAIL_USERNAME = "username";

  @Property(label="password", description = "password")

  public static final String EMAIL_PASSWORD = "password";

  @Property(label="template path", description = "Email template path")

  public static final String EMAIL_TEMPLATE = "template_path";

  //local variables to hold OSGI config values

  private String server;

  private String port;

  private String username;

  private String password;

  private String template_path;

  @Activate

  protected void activate(Map<String,Object> properties){

  LOG.info("entered the activate method");

  configure(properties,"Activated");

  }

  @Modified

  protected void modified(Map<String, Object> properties){

  configure(properties,"Modified");

  }

  @Deactivate

  protected void deactivated(Map<String, Object> properties){

  }

  protected void configure(Map<String,Object> properties,String status){

  server = PropertiesUtil.toString(properties.get(SMTP_SERVER),StringUtils.EMPTY);

  port = PropertiesUtil.toString(properties.get(SMTP_PORT), StringUtils.EMPTY);

  username = PropertiesUtil.toString(properties.get(EMAIL_USERNAME), StringUtils.EMPTY);

  password = PropertiesUtil.toString(properties.get(EMAIL_PASSWORD), StringUtils.EMPTY);

  template_path = PropertiesUtil.toString(properties.get(EMAIL_TEMPLATE), StringUtils.EMPTY);

  LOG.info("configured the details:"+server+" port:"+port); // configured values appear

  }

  //send function should be here

  public void send(String toEmail, String fromEmail, String aSubject, String aMessage,Resource templateResource)

  {

  try

  {

 

  // Recipient's email ID needs to be mentioned.

  String to = toEmail;

  LOG.info("to address"+ toEmail);

  // Sender's email ID needs to be mentioned

  String from = fromEmail;

  LOG.info("from address"+ fromEmail);

  LOG.info("subject"+ aSubject);

  LOG.info("server"+ server);// appears null in the log

  LOG.info("port"+ port);// appears null in the log

  // Reply To

  //Address [] ad = new InternetAddress;

  // Get system properties

  java.util.Properties properties = System.getProperties();

  // Setup mail server (Depending upon your

  // Mail server - you may need more props here

  properties.setProperty("mail.smtp.auth", "true");

  properties.setProperty("mail.smtp.starttls.enable", "true");

  properties.setProperty("mail.smtp.host", server);

  properties.setProperty("mail.smtp.port", port);

  // Get the default Session object.

  Session session = Session.getInstance(properties,

  new javax.mail.Authenticator() {

  protected PasswordAuthentication getPasswordAuthentication() {

  return new PasswordAuthentication(username, password);

  }

  });

  // Create a default MimeMessage object.

  MimeMessage message = new MimeMessage(session);

  // Set From: header field of the header.

  message.setFrom(new InternetAddress(from));

  //Set Replyto: header to reply to this address

  message.setReplyTo(new Address[]

  {new InternetAddress(from)});

  // Set To: header field of the header.

  message.addRecipient(Message.RecipientType.TO,

  new InternetAddress(to));

  // Set Subject: header field

  message.setSubject(aSubject);

  // Now set the actual message

 

  message.setText(aMessage);

  // Send message

  Transport.send(message);

  LOG.info("sent message");

  }

  catch (Exception ex)

  {

  ex.printStackTrace();

  }

  }

August 23, 2017

I am in a hurry to complete this task. It would be really helpful if you could point out the error for now so that I can correct it asap. Thanks.

August 23, 2017

I have a small query about the component attributes. what happens when the immediate attribute is set to false? When can it be activated if configured as false?

viveksachdeva
Community Advisor
viveksachdevaCommunity AdvisorAccepted solution
Community Advisor
August 24, 2017

mallikac49331008 You should not instantiate service object

like:EmailService mailService = new EmailServiceImpl();

You already have reference to it as emailService. Just use that to call send mail method.

Moreover, you dont seem to have set the default values of the properties. You can ser values using http://www.aemcq5tutorials.com/tutorials/custom-osgi-configuration-aem/ or by creating a config node corresponding to the component pid.

https://www.youtube.com/watch?v=FF8wWILATMM

viveksachdeva
Community Advisor
Community Advisor
August 24, 2017
August 24, 2017

Thanks Vivek, it worked once I removed the instantiation. 

magic_loc
October 16, 2017

Please change:

  @Reference

    private transient EmailService emailService;

to

  @Reference

    private  EmailService emailService;

Regards

June 1, 2018

Thanks magic loc, It worked!