1 24 package org.riotfamily.riot.job.support; 25 26 import org.riotfamily.riot.dao.RiotDao; 27 import org.riotfamily.riot.job.Job; 28 import org.riotfamily.riot.job.JobContext; 29 import org.riotfamily.riot.job.JobCreationException; 30 import org.riotfamily.riot.job.JobDescription; 31 import org.springframework.beans.factory.BeanNameAware; 32 import org.springframework.transaction.PlatformTransactionManager; 33 import org.springframework.transaction.TransactionStatus; 34 import org.springframework.transaction.support.TransactionCallback; 35 import org.springframework.transaction.support.TransactionTemplate; 36 37 public abstract class AbstractJob implements Job, BeanNameAware { 38 39 private String beanName; 40 41 private RiotDao dao; 42 43 private PlatformTransactionManager transactionManager; 44 45 public void setDao(RiotDao dao) { 46 this.dao = dao; 47 } 48 49 protected RiotDao getDao() { 50 return this.dao; 51 } 52 53 public void setTransactionManager(PlatformTransactionManager transactionManager) { 54 this.transactionManager = transactionManager; 55 } 56 57 public boolean isConcurrent() { 58 return false; 59 } 60 61 public boolean isRepeatable() { 62 return true; 63 } 64 65 public void setBeanName(String beanName) { 66 this.beanName = beanName; 67 } 68 69 public JobDescription setup(final String objectId) { 70 if (transactionManager != null) { 71 return (JobDescription) new TransactionTemplate(transactionManager).execute(new TransactionCallback() { 72 public Object doInTransaction(TransactionStatus status) { 73 return setupInternal(objectId); 74 } 75 }); 76 } 77 else { 78 return setupInternal(objectId); 79 } 80 } 81 82 protected final JobDescription setupInternal(String objectId) { 83 JobDescription jd = new JobDescription(); 84 jd.setName(beanName); 85 try { 86 initDescription(jd, loadObject(objectId)); 87 } 88 catch (Exception e) { 89 throw new JobCreationException("Job creation failed.", e); 90 } 91 return jd; 92 } 93 94 protected void initDescription(JobDescription jd, Object entity) throws Exception { 95 } 96 97 public final void execute(final JobContext context) { 98 if (transactionManager != null) { 99 new TransactionTemplate(transactionManager).execute(new TransactionCallback() { 100 public Object doInTransaction(TransactionStatus status) { 101 execute(context, loadObject(context.getObjectId())); 102 return null; 103 } 104 }); 105 } 106 else { 107 execute(context, loadObject(context.getObjectId())); 108 } 109 } 110 111 protected Object loadObject(String objectId) { 112 if (objectId != null) { 113 return dao.load(objectId); 114 } 115 return null; 116 } 117 118 protected abstract void execute(JobContext context, Object entity); 119 120 public void tearDown(String objectId) { 121 } 122 123 } 124 | Popular Tags |