Java tutorial
/** * Product : Hiperium Project * Architect: Andres Solorzano. * Created : 08-05-2009 - 23:30:00 * * The contents of this file are copyrighted by Andres Solorzano * and it is protected by the license: "GPL V3." You can find a copy of this * license at: http://www.hiperium.com/about/licence.html * * Copyright 2014 Andres Solorzano. All rights reserved. * */ package com.hiperium.bo.control.impl; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.annotation.Resource; import javax.ejb.Remote; import javax.ejb.ScheduleExpression; import javax.ejb.Stateless; import javax.ejb.Timeout; import javax.ejb.Timer; import javax.ejb.TimerConfig; import javax.ejb.TimerService; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; import javax.inject.Inject; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import org.apache.commons.beanutils.BeanPropertyValueChangeClosure; import org.apache.commons.collections.CollectionUtils; import com.hiperium.bo.control.TaskBO; import com.hiperium.bo.generic.GenericBusinessObject; import com.hiperium.commons.EnumHiperiumTier; import com.hiperium.commons.EnumI18N; import com.hiperium.commons.HiperiumTier; import com.hiperium.commons.bean.BeanUtils; import com.hiperium.commons.exception.EnumInformationException; import com.hiperium.commons.exception.InformationException; import com.hiperium.commons.log.HiperiumLogger; import com.hiperium.model.EnumDeviceAction; import com.hiperium.model.EnumFrequency; import com.hiperium.model.control.Device; import com.hiperium.model.control.Task; /** * This service is the implementation of the interface TaskLocal * and manages all actions needed for the task management. * * @author Andres Solorzano * */ @Stateless @Remote(TaskBO.class) public class TaskBOImpl extends GenericBusinessObject implements TaskBO { /** The property log. */ @Inject @HiperiumTier(EnumHiperiumTier.BUSINESS) private HiperiumLogger log; /** EJB Timer Service Resource. */ @Resource private TimerService timerService; /** * {@inheritDoc} */ @Override public void create(@NotNull Task task, @NotNull String sessionId) throws InformationException { this.log.debug("create - START"); if (task.getExecutionDate().after(new Date())) { super.getDaoFactory().getTaskDAO().create(task); if (EnumFrequency.CUSTOM.equals(task.getFrequency())) { this.createCalendarTimer(task); } else if (EnumFrequency.ONCE.equals(task.getFrequency())) { this.createSingleTimer(task); } else { this.createIntervalTimer(task); } } else { throw InformationException.generate(EnumI18N.COMMON, EnumInformationException.TASK_DATE_TIME, super.getSessionManager().findUserLocale(sessionId)); } this.log.debug("create - END"); } /** * {@inheritDoc} */ @Override public Task update(@NotNull Task task, @NotNull String sessionId) throws InformationException { this.log.debug("homeSelection - START"); this.delete(task.getId(), sessionId); this.create(task, sessionId); this.log.debug("homeSelection - END"); return task; } /** * {@inheritDoc} */ @Override public void delete(@NotNull @Min(value = 1L) Long id, @NotNull String sessionId) throws InformationException { this.log.debug("delete - START"); super.getDaoFactory().getTaskDAO().delete(id); super.getDaoFactory().getTaskDAO().flushEntityManager(); Timer t = this.findTimer(id); if (t != null) { t.cancel(); this.log.debug("delete: \"" + t + "\" canceled."); } this.log.debug("delete - END"); } /** * {@inheritDoc} */ @Override public List<Task> updateRegisterState(@NotNull List<Task> list, boolean newState, @NotNull String sessionId) throws InformationException { this.log.debug("changeRegisterState - START"); if (list != null && !list.isEmpty()) { List<Task> actualList = new ArrayList<Task>(); for (Task task : list) { Task actual = super.getDaoFactory().getTaskDAO().findById(task.getId(), false, true); actualList.add(actual); } list.clear(); BeanPropertyValueChangeClosure closure = new BeanPropertyValueChangeClosure("active", newState); CollectionUtils.forAllDo(actualList, closure); for (Task task : actualList) { Task updated = super.getDaoFactory().getTaskDAO().update(task); Task basic = new Task(); BeanUtils.copyProperties(updated, basic); list.add(basic); } } this.log.debug("changeRegisterState - END"); return list; } /** * {@inheritDoc} */ @Override public Task findById(@NotNull @Min(value = 1L) Long id, boolean lock, @NotNull String sessionId) throws InformationException { return super.getDaoFactory().getTaskDAO().findById(id, lock, true); } /** * {@inheritDoc} */ @Override public List<Task> findByDeviceId(@NotNull @Min(value = 1L) Long deviceId, @NotNull String sessionId) throws InformationException { return super.getDaoFactory().getTaskDAO().findByDeviceId(deviceId); } /** * {@inheritDoc} */ @Timeout public void excecute(Timer timer) { Long taskId = (Long) timer.getInfo(); this.log.debug("excecuteTask - START: task ID = " + taskId); try { Task task = super.getDaoFactory().getTaskDAO().findById(taskId, false, true); if (task != null && task.getActive()) { List<Device> deviceList = super.getDaoFactory().getDeviceDAO().findByTaskId(taskId); for (Device device : deviceList) { if (task.getAction().equals(EnumDeviceAction.ACTIVATE) || task.getAction().equals(EnumDeviceAction.LOCK)) { device.setActive(true); } else if (task.getAction().equals(EnumDeviceAction.DEACTIVATE) || task.getAction().equals(EnumDeviceAction.UNLOCK)) { device.setActive(false); } super.getDaoFactory().getDeviceDAO().update(device); // TODO: SEND TO THE HIPERIUM CLOUD // DeviceGsonConverter jsonConverter = new DeviceGsonConverter(); // Long homeId = this.zoneRepositoryLocal.findHomeIdByZoneId(device.getZoneId(), // EnumPlatformSessionID.INSTANCE.getSessionId()); } //CREATE A NEW TIMER SERVICE FOR FREQUENCY MORE THAN DAILY if (EnumFrequency.WEEKLY.equals(task.getFrequency()) || EnumFrequency.MONTHLY.equals(task.getFrequency()) || EnumFrequency.QUARTERLY.equals(task.getFrequency()) || EnumFrequency.SEMIANNUAL.equals(task.getFrequency()) || EnumFrequency.ANNUAL.equals(task.getFrequency())) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); switch (task.getFrequency()) { case WEEKLY: this.log.debug("excecuteTask - WEEKLY"); calendar.add(Calendar.DAY_OF_MONTH, 7); break; case MONTHLY: this.log.debug("excecuteTask - MONTHLY"); calendar.add(Calendar.MONTH, 1); break; case QUARTERLY: this.log.debug("excecuteTask - QUARTERLY"); calendar.add(Calendar.MONTH, 3); break; case SEMIANNUAL: this.log.debug("excecuteTask - SEMIANNUAL"); calendar.add(Calendar.MONTH, 6); break; case ANNUAL: this.log.debug("excecuteTask - ANNUAL"); calendar.add(Calendar.YEAR, 1); break; default: break; } // We recreate the task with the new manipulated date time. this.timerService.createSingleActionTimer(calendar.getTime(), new TimerConfig(task.getId(), true)); } } } catch (Exception e) { this.log.error("Error: " + e.getMessage()); } timer.cancel(); this.log.debug("excecuteTask - END"); } /** * * @param task */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void createSingleTimer(Task task) { this.log.debug("createSingleTimer - START"); this.timerService.createSingleActionTimer(task.getExecutionDate(), new TimerConfig(task.getId(), true)); this.log.debug("createSingleTimer - END"); } /** * * @param task * @throws InformationException */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void createCalendarTimer(Task task) throws InformationException { this.log.debug("createCalendarTimer - START"); ScheduleExpression expression = new ScheduleExpression(); // TODO: Create CRON TASK based on task.getCronTask() parameter. this.timerService.createCalendarTimer(expression, new TimerConfig(task.getId(), true)); this.log.debug("createCalendarTimer - END"); } /** * * @param task */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private void createIntervalTimer(Task task) { this.log.debug("createIntervalTimer - START: " + task.getExecutionDate()); Long interval = 0L; switch (task.getFrequency()) { case EVERY_MIMUTE: this.log.debug("createIntervalTimer - EVERY_MIMUTE"); interval = 60000L; break; case QUARTER_HOUR: this.log.debug("createIntervalTimer - QUARTER_HOUR"); interval = 900000L; break; case HALF_HOUR: this.log.debug("createIntervalTimer - HALF_HOUR"); interval = 1800000L; break; case HOURLY: this.log.debug("createIntervalTimer - HOURLY"); interval = 3600000L; break; case DAILY: this.log.debug("createIntervalTimer - DAILY"); interval = 86400000L; break; default: break; } this.log.debug("Interval in milliseconds: " + interval); this.timerService.createIntervalTimer(task.getExecutionDate(), interval, new TimerConfig(task.getId(), true)); this.log.debug("createIntervalTimer - END"); } /** * * @param taskId * @return */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) private Timer findTimer(Long taskId) { this.log.debug("findTimer - START"); Timer timer = null; Collection<Timer> timers = this.timerService.getTimers(); if (timers != null) { for (Iterator<Timer> iterator = timers.iterator(); iterator.hasNext();) { Timer t = iterator.next(); try { if (taskId.equals((Long) t.getInfo())) { timer = t; } } catch (Exception e) { this.log.debug("ERROR: " + e.getMessage()); } } } this.log.debug("findTimer - END"); return timer; } }