Cron Jobs
SAP Commerce provides a means to set up regular tasks. With these tasks, or cron jobs, you can repeatedly perform complex business logic at particular times and intervals.
You may want to perform an inventory every Sunday at midnight, for example, or notify the web administrator of the peak loads on the servers every hour. You can achieve this through a combination of dedicated classes for the business logic, and the embedded cron job management functionality of SAP Commerce.
The first step in implementing a cron job is to place your business logic in a class that extends AbstractJobPerformable. You then develop a new, simple service to provide access to the news items, and encapsulate that business logic in a job class. The steps are similar to those you took to create the band service, and serve to reinforce this pattern.
The SAP Commerce platform ships with a useful email utility class, MailUtils, that simplifies the sending of e-mails with commons mail API. You make use of the MailUtils class to create an e-mail message object populated with values from the local.properties file in your config directory.
Write the Business Logic for a Cron Job
Write a cron job to send daily news summaries.
Prerequisites
public void testSendNewsJobIntegrationTest() {
assertTrue( checkTestSuiteXMLMatches("(.*)testsuite errors=\"0\" failures=\"0\" (.*) name=\"SendNewsJobIntegrationTest\" package=\"concerttours.jobs\" tests=\"2\" (.*)" ));
}
Before you begin this step, run the test to confirm that it fails by executing this command:
cd $HYBRIS_HOME_DIR/hybris123; mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testSendNewsJobIntegrationTest test
cd %HYBRIS_HOME_DIR%\hybris123 & mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testSendNewsJobIntegrationTest test
Procedure
- Stop SAP Commerce.
cd $HYBRIS_HOME_DIR/hybris/bin/platform; ./hybrisserver.sh stop
cd %HYBRIS_HOME_DIR%\hybris\bin\platform & hybrisserver.bat stop
- Create a news data access interface in <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/daos/NewsDAO.java
package concerttours.daos; import java.util.Date; import java.util.List; import concerttours.model.NewsModel; public interface NewsDAO { List<NewsModel> getNewsOfTheDay(Date date); }SAP Commerce 123 Interactive Shortcut: If you are unable to create the news data access interface yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/daos/NewsDAO.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/NewsDAO.java
ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/NewsDAO.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/daos/NewsDAO.java
echo f | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\daos\NewsDAO.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\daos\NewsDAO.java
- Create a news data access implementation in <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/daos/impl/DefaultNewsDAO.java
package concerttours.daos.impl; import de.hybris.platform.servicelayer.search.FlexibleSearchQuery; import de.hybris.platform.servicelayer.search.FlexibleSearchService; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import concerttours.daos.NewsDAO; import concerttours.model.NewsModel; @Component(value = "newsDAO") public class DefaultNewsDAO implements NewsDAO { private static final String SQL_DATE_FORMAT = "yyyy-MM-dd"; @Autowired private FlexibleSearchService flexibleSearchService; @Override public List<NewsModel> getNewsOfTheDay(final Date date) { if (date == null) { return Collections.emptyList(); } final String theDay = new SimpleDateFormat(SQL_DATE_FORMAT).format(date); final String theNextDay = new SimpleDateFormat(SQL_DATE_FORMAT).format(oneDayAfter(date)); final String queryString = // "SELECT {p:" + NewsModel.PK + "} "// + "FROM {" + NewsModel._TYPECODE + " AS p} " // + "WHERE {date} >= DATE \'" + theDay + "\' "// + "AND {date} <= DATE \'" + theNextDay + "\'"; final FlexibleSearchQuery query = new FlexibleSearchQuery(queryString); return flexibleSearchService.<NewsModel> search(query).getResult(); } private Date oneDayAfter(final Date date) { final Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, 1); return cal.getTime(); } }SAP Commerce 123 Interactive Shortcut: If you are unable to create the implementation yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/daos/impl/DefaultNewsDAO.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/impl/DefaultNewsDAO.java
ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/daos/impl/DefaultNewsDAO.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/daos/impl/DefaultNewsDAO.java
echo f | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\daos\impl\DefaultNewsDAO.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\daos\impl\DefaultNewsDAO.java
- Create a news service interface called NewsService.java in <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/service
package concerttours.service; import java.util.Date; import java.util.List; import concerttours.model.NewsModel; public interface NewsService { List<NewsModel> getNewsOfTheDay(Date date); }SAP Commerce 123 Interactive Shortcut: If you are unable to create the news service interface yourself or you want to skip this step, copy <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/NewsService.java into <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/service
ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/NewsService.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/service/NewsService.java
echo a | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\service\NewsService.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\service
- Create a news service implementation called DefaultNewsService.java in <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/service/impl
package concerttours.service.impl; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import concerttours.daos.NewsDAO; import concerttours.model.NewsModel; import concerttours.service.NewsService; public class DefaultNewsService implements NewsService { @Autowired private NewsDAO newsDAO; public void setNewsDAO(final NewsDAO newsDAO) { this.newsDAO = newsDAO; } @Override public List<NewsModel> getNewsOfTheDay(final Date date) { return newsDAO.getNewsOfTheDay(date); } }SAP Commerce 123 Interactive Shortcut: If you are unable to create the implementation yourself or you want to skip this step, copy <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/impl/DefaultNewsService.java into <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/service/impl
ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/service/impl/DefaultNewsService.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/service/impl/DefaultNewsService.java
echo a | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\service\impl\DefaultNewsService.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\service\impl
- Configure the email server by adding email server properties to the local.properties file.
The example shows how you would do this with a generic email account. Update the SMTP server, username, and password to match yours.
- Add the following properties to the local.properties file in the config directory, adjusting them making sure to replace <smtp.email.com>, <your username>, <your password>, and <your email address> with your username, password, and email address. If port 465 is not available, change the port.
mail.from=concerttours-no-reply@hybris.de mail.replyto=concerttours-no-reply@hybris.de mail.smtp.server=smtp.email.com mail.smtp.port=465 mail.smtp.user=<your username> mail.smtp.password=<your password> news_summary_mailing_address=<your email address>
- Update your email account to (temporarily) allow less secure applications to access it by selecting the Allow less secure apps option.
SAP Commerce 123 Interactive Shortcut: If you are unable to add the properties yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/config/local.properties with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/resources/config/local.properties
cat $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/resources/config/local.properties >> $HYBRIS_HOME_DIR/hybris/config/local.properties
type %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\resources\config\local.properties >> %HYBRIS_HOME_DIR%\hybris\config\local.properties
- Add the following properties to the local.properties file in the config directory, adjusting them making sure to replace <smtp.email.com>, <your username>, <your password>, and <your email address> with your username, password, and email address. If port 465 is not available, change the port.
- Create the job class.
package concerttours.jobs; import de.hybris.platform.cronjob.enums.CronJobResult; import de.hybris.platform.cronjob.enums.CronJobStatus; import de.hybris.platform.cronjob.model.CronJobModel; import de.hybris.platform.servicelayer.config.ConfigurationService; import de.hybris.platform.servicelayer.cronjob.AbstractJobPerformable; import de.hybris.platform.servicelayer.cronjob.PerformResult; import de.hybris.platform.util.mail.MailUtils; import java.util.Date; import java.util.List; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Required; import concerttours.model.NewsModel; import concerttours.service.NewsService; public class SendNewsJob extends AbstractJobPerformable<CronJobModel> { private static final Logger LOG = Logger.getLogger(SendNewsJob.class); private NewsService newsService; private ConfigurationService configurationService; @Required public NewsService getNewsService() { return newsService; } @Required public ConfigurationService getConfigurationService() { return configurationService; } @Required public void setNewsService(final NewsService newsService) { this.newsService = newsService; } @Required public void setConfigurationService(final ConfigurationService configurationService) { this.configurationService = configurationService; } @Override public PerformResult perform(final CronJobModel cronJob) { LOG.info("Sending news mails. Note that org.apache.commons.mail.send() can block if behind a firewall/proxy."); final List<NewsModel> newsItems = getNewsService().getNewsOfTheDay(new Date()); if (newsItems.isEmpty()) { LOG.info("No news items for today, skipping send of ranking mails"); return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED); } final StringBuilder mailContentBuilder = new StringBuilder(2000); int index = 1; mailContentBuilder.append("Todays news summary:\n\n"); for (final NewsModel news : newsItems) { mailContentBuilder.append(index++); mailContentBuilder.append(". "); mailContentBuilder.append(news.getHeadline()); mailContentBuilder.append("\n"); mailContentBuilder.append(news.getContent()); mailContentBuilder.append("\n\n"); } try { sendEmail(mailContentBuilder.toString()); } catch (final EmailException e) { LOG.error("Problem sending new email. Note that org.apache.commons.mail.send() can block if behind a firewall/proxy.)"); LOG.error("Problem sending new email.", e); return new PerformResult(CronJobResult.FAILURE, CronJobStatus.FINISHED); } return new PerformResult(CronJobResult.SUCCESS, CronJobStatus.FINISHED); } private void sendEmail(final String message) throws EmailException { final String subject = "Daily News Summary"; // get mail service configuration final Email email = MailUtils.getPreConfiguredEmail(); //send message Configuration config = getConfigurationService().getConfiguration(); String recipient = config.getString("news_summary_mailing_address", null); email.addTo(recipient); email.setSubject(subject); email.setMsg(message); email.setTLS(true); email.send(); LOG.info(subject); LOG.info(message); } }SAP Commerce 123 Interactive Shortcut: If you are unable to create the job class yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/src/concerttours/jobs/SendNewsJob.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/src/concerttours/jobs/SendNewsJob.java
ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/src/concerttours/jobs/SendNewsJob.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/src/concerttours/jobs/SendNewsJob.java
echo f | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\src\concerttours\jobs\SendNewsJob.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\src\concerttours\jobs\SendNewsJob.java
- Register the service and job in Spring.
<alias name="defaultNewsService" alias="newsService" /> <bean id="defaultNewsService" class="concerttours.service.impl.DefaultNewsService"> <property name="newsDAO" ref="newsDAO" /> </bean> <bean id="sendNewsJob" class="concerttours.jobs.SendNewsJob" parent="abstractJobPerformable"> <property name="newsService" ref="newsService" /> <property name="configurationService" ref="configurationService" /> </bean>SAP Commerce 123 Interactive Shortcut: If you are unable to register the service and job yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/resources/concerttours-spring.xml with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/resources/concerttours-spring-withNewsService.xml
cp $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/resources/concerttours-spring-withNewsService.xml $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/resources/concerttours-spring.xml
copy /y %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\resources\concerttours-spring-withNewsService.xml %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\resources\concerttours-spring.xml
- Write an integration test to test successful job creation.
package concerttours.jobs; import de.hybris.bootstrap.annotations.IntegrationTest; import de.hybris.platform.cronjob.enums.CronJobResult; import de.hybris.platform.servicelayer.ServicelayerTransactionalTest; import de.hybris.platform.servicelayer.cronjob.PerformResult; import de.hybris.platform.servicelayer.model.ModelService; import java.lang.InterruptedException; import java.util.Date; import java.util.concurrent.TimeUnit; import de.hybris.platform.core.Registry; import org.springframework.jdbc.core.JdbcTemplate; import javax.annotation.Resource; import org.junit.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import concerttours.model.NewsModel; @IntegrationTest public class SendNewsJobIntegrationTest extends ServicelayerTransactionalTest { @Resource private ModelService modelService; @Resource private SendNewsJob sendNewsJob; @Before public void setUp() throws Exception { try { Thread.sleep(TimeUnit.SECONDS.toMillis(1)); new JdbcTemplate(Registry.getCurrentTenant().getDataSource()).execute("CHECKPOINT"); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); } catch (InterruptedException exc) {} } @Test public void testNoNewsItems() { final PerformResult result = sendNewsJob.perform(null); Assert.assertEquals("Job did not perform correctly", CronJobResult.SUCCESS, result.getResult()); } @Test public void testSendingNews() throws Exception { final NewsModel news1 = modelService.create(NewsModel.class); news1.setHeadline("test headline 1"); news1.setContent("test content 1"); news1.setDate(new Date()); final NewsModel news2 = modelService.create(NewsModel.class); news2.setHeadline("test headline 2"); news2.setContent("test content 2"); news2.setDate(new Date()); modelService.saveAll(); final PerformResult result = sendNewsJob.perform(null); Assert.assertEquals("Job did not perform correctly", CronJobResult.SUCCESS, result.getResult()); } @After public void tearDown() { } }SAP Commerce 123 Interactive Shortcut: If you are unable to create the integration test yourself or you want to skip this step, replace <HYBRIS_HOME_DIR>/hybris/bin/custom/concerttours/testsrc/concerttours/jobs/SendNewsJobIntegrationTest.java with the contents of <HYBRIS_HOME_DIR>/hybris123/src/main/webapp/resources/concerttours/testsrc/concerttours/jobs/SendNewsJobIntegrationTest.java
ditto $HYBRIS_HOME_DIR/hybris123/src/main/webapp/resources/concerttours/testsrc/concerttours/jobs/SendNewsJobIntegrationTest.java $HYBRIS_HOME_DIR/hybris/bin/custom/concerttours/testsrc/concerttours/jobs/SendNewsJobIntegrationTest.java
echo f | xcopy %HYBRIS_HOME_DIR%\hybris123\src\main\webapp\resources\concerttours\testsrc\concerttours\jobs\SendNewsJobIntegrationTest.java %HYBRIS_HOME_DIR%\hybris\bin\custom\concerttours\testsrc\concerttours\jobs\SendNewsJobIntegrationTest.java
- Rebuild SAP Commerce with Ant.
cd $HYBRIS_HOME_DIR/hybris/bin/platform; ant clean all
cd %HYBRIS_HOME_DIR%\hybris\bin\platform & ant clean all
- Initialize your test tenant.
cd $HYBRIS_HOME_DIR/hybris/bin/platform; ant yunitinit
cd %HYBRIS_HOME_DIR%\hybris\bin\platform & ant yunitinit
- Run the integration test and confirm that SendNewsJobIntegrationTest passes.
ant integrationtests -Dtestclasses.packages="concerttours.*"
ant integrationtests -Dtestclasses.packages=concerttours.*
- View the test results at <HYBRIS_HOME_DIR>/hybris/log/junit/index.html.
- Run the testSendNewsJobIntegrationTest acceptance test again and confirm that it now passes.
cd $HYBRIS_HOME_DIR/hybris123; mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testSendNewsJobIntegrationTest test
cd %HYBRIS_HOME_DIR%\hybris123 & mvn -Dtest=com.hybris.hybris123.runtime.tests.Hybris123Tests#testSendNewsJobIntegrationTest test
- Commit the changes to your local Git repository.
cd $HYBRIS_HOME_DIR/hybris; git add . ; git commit -m "Write the Business Logic for a Cron Job"
cd %HYBRIS_HOME_DIR%\hybris & git add . & git commit -m "Write the Business Logic for a Cron Job"