下面列出了怎么用org.quartz.ObjectAlreadyExistsException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* <p>
* Trigger the identified <code>{@link org.quartz.Job}</code> (execute it
* now) - with a non-volatile trigger.
* </p>
*/
@SuppressWarnings("deprecation")
public void triggerJob(JobKey jobKey, JobDataMap data) throws SchedulerException {
validateState();
OperableTrigger trig = (OperableTrigger) newTrigger().withIdentity(newTriggerId(), Scheduler.DEFAULT_GROUP).forJob(jobKey).build();
trig.computeFirstFireTime(null);
if(data != null) {
trig.setJobDataMap(data);
}
boolean collision = true;
while (collision) {
try {
resources.getJobStore().storeTrigger(trig, false);
collision = false;
} catch (ObjectAlreadyExistsException oaee) {
trig.setKey(new TriggerKey(newTriggerId(), Scheduler.DEFAULT_GROUP));
}
}
notifySchedulerThread(trig.getNextFireTime().getTime());
notifySchedulerListenersSchduled(trig);
}
/**
* <p>
* Store and schedule the identified <code>{@link org.quartz.spi.OperableTrigger}</code>
* </p>
*/
public void triggerJob(OperableTrigger trig) throws SchedulerException {
validateState();
trig.computeFirstFireTime(null);
boolean collision = true;
while (collision) {
try {
resources.getJobStore().storeTrigger(trig, false);
collision = false;
} catch (ObjectAlreadyExistsException oaee) {
trig.setKey(new TriggerKey(newTriggerId(), Scheduler.DEFAULT_GROUP));
}
}
notifySchedulerThread(trig.getNextFireTime().getTime());
notifySchedulerListenersSchduled(trig);
}
/**
* <p>
* Store the given <code>{@link org.quartz.JobDetail}</code> and <code>{@link org.quartz.Trigger}</code>.
* </p>
*
* @param newJob
* The <code>JobDetail</code> to be stored.
* @param newTrigger
* The <code>Trigger</code> to be stored.
* @throws ObjectAlreadyExistsException
* if a <code>Job</code> with the same name/group already
* exists.
*/
public void storeJobAndTrigger(final SchedulingContext ctxt, final JobDetail newJob,
final Trigger newTrigger)
throws ObjectAlreadyExistsException, JobPersistenceException {
executeInLock(
(isLockOnInsert()) ? LOCK_TRIGGER_ACCESS : null,
new VoidTransactionCallback() {
public void execute(Connection conn) throws JobPersistenceException {
if (newJob.isVolatile() && !newTrigger.isVolatile()) {
JobPersistenceException jpe =
new JobPersistenceException(
"Cannot associate non-volatile trigger with a volatile job!");
jpe.setErrorCode(SchedulerException.ERR_CLIENT_ERROR);
throw jpe;
}
storeJob(conn, ctxt, newJob, false);
storeTrigger(conn, ctxt, newTrigger, newJob, false,
Constants.STATE_WAITING, false, false);
}
});
}
private void storeJob(final ODatabaseDocumentTx db, final JobDetail jobDetail, final boolean replaceExisting)
throws JobPersistenceException
{
log.debug("Store job: jobDetail={}, replaceExisting={}", jobDetail, replaceExisting);
JobDetailEntity entity = jobDetailEntityAdapter.readByKey(db, jobDetail.getKey());
if (entity == null) {
// no existing entity, add new one
entity = new JobDetailEntity(jobDetail);
jobDetailEntityAdapter.addEntity(db, entity);
}
else {
// otherwise entity exists, maybe replace if allowed
if (replaceExisting) {
entity.setValue(jobDetail);
jobDetailEntityAdapter.editEntity(db, entity);
}
else {
throw new ObjectAlreadyExistsException(jobDetail);
}
}
}
public void init() throws ParserConfigurationException, XPathException, ParseException, IOException, ValidationException, SchedulerException, SAXException, ClassNotFoundException {
boolean noFiles = files == null || files.isEmpty();
if (noFiles || !schedulerManager.isAutoProvisioning()) {
log.info("Not auto provisioning jobs: "+ ((noFiles)?"no files.":String.join(", ", files)));
return;
}
Scheduler scheduler = schedulerManager.getScheduler();
ClassLoadHelper clh = new CascadingClassLoadHelper();
clh.initialize();
for (String file : files ) {
XMLSchedulingDataProcessor proc = new XMLSchedulingDataProcessor(clh);
InputStream in = getClass().getResourceAsStream(file);
if (in == null) {
throw new IllegalArgumentException("Couldn't find resource on classpath: "+ file);
}
try {
proc.processStreamAndScheduleJobs(in, file, scheduler);
log.info("Successfully provisioned jobs/triggers from :"+ file);
} catch (ObjectAlreadyExistsException e) {
log.info("Not fully processing: "+ file+ " because some parts already exist");
}
}
}
/**
* Stores job in redis.
*
* @param newJob the new job
* @param replaceExisting the replace existing
* @param jedis thread-safe redis connection
* @throws ObjectAlreadyExistsException
*/
private void storeJob(JobDetail newJob, boolean replaceExisting, Jedis jedis)
throws ObjectAlreadyExistsException {
String jobHashKey = createJobHashKey(newJob.getKey().getGroup(), newJob.getKey().getName());
String jobDataMapHashKey = createJobDataMapHashKey(newJob.getKey().getGroup(), newJob.getKey().getName());
String jobGroupSetKey = createJobGroupSetKey(newJob.getKey().getGroup());
if (jedis.exists(jobHashKey) && !replaceExisting)
throw new ObjectAlreadyExistsException(newJob);
Map<String, String> jobDetails = new HashMap<>();
jobDetails.put(DESCRIPTION, newJob.getDescription() != null ? newJob.getDescription() : "");
jobDetails.put(JOB_CLASS, newJob.getJobClass().getName());
jobDetails.put(IS_DURABLE, Boolean.toString(newJob.isDurable()));
jobDetails.put(BLOCKED_BY, "");
jobDetails.put(BLOCK_TIME, "");
jedis.hmset(jobHashKey, jobDetails);
if (newJob.getJobDataMap() != null && !newJob.getJobDataMap().isEmpty())
jedis.hmset(jobDataMapHashKey, getStringDataMap(newJob.getJobDataMap()));
jedis.sadd(JOBS_SET, jobHashKey);
jedis.sadd(JOB_GROUPS_SET, jobGroupSetKey);
jedis.sadd(jobGroupSetKey, jobHashKey);
}
protected void addTrigger(Trigger trigger) {
try {
if (UNSCHEDULED_GROUP.equals(trigger.getGroup())) {
LOG.error("Triggers should not be specified for jobs in the unscheduled group - not adding trigger: " + trigger.getName());
}
else {
LOG.info("Adding trigger: " + trigger.getName());
try {
scheduler.scheduleJob(trigger);
}
catch (ObjectAlreadyExistsException ex) {
}
}
}
catch (SchedulerException e) {
throw new RuntimeException("Caught exception while adding trigger: " + trigger.getFullName(), e);
}
}
public void init() throws ParserConfigurationException, XPathException, ParseException, IOException, ValidationException, SchedulerException, SAXException, ClassNotFoundException {
boolean noFiles = files == null || files.isEmpty();
if (noFiles || !schedulerManager.isAutoProvisioning()) {
log.info("Not auto provisioning jobs: "+ ((noFiles)?"no files.":String.join(", ", files)));
return;
}
Scheduler scheduler = schedulerManager.getScheduler();
ClassLoadHelper clh = new CascadingClassLoadHelper();
clh.initialize();
for (String file : files ) {
XMLSchedulingDataProcessor proc = new XMLSchedulingDataProcessor(clh);
InputStream in = getClass().getResourceAsStream(file);
if (in == null) {
throw new IllegalArgumentException("Couldn't find resource on classpath: "+ file);
}
try {
proc.processStreamAndScheduleJobs(in, file, scheduler);
log.info("Successfully provisioned jobs/triggers from :"+ file);
} catch (ObjectAlreadyExistsException e) {
log.info("Not fully processing: "+ file+ " because some parts already exist");
}
}
}
/**
* Add the given trigger to the Scheduler, if it doesn't already exist.
* Overwrites the trigger in any case if "overwriteExistingJobs" is set.
* @param trigger the trigger to add
* @return {@code true} if the trigger was actually added,
* {@code false} if it already existed before
* @see #setOverwriteExistingJobs
*/
private boolean addTriggerToScheduler(Trigger trigger) throws SchedulerException {
boolean triggerExists = (getScheduler().getTrigger(trigger.getKey()) != null);
if (triggerExists && !this.overwriteExistingJobs) {
return false;
}
// Check if the Trigger is aware of an associated JobDetail.
JobDetail jobDetail = (JobDetail) trigger.getJobDataMap().remove("jobDetail");
if (triggerExists) {
if (jobDetail != null && !this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) {
this.jobDetails.add(jobDetail);
}
getScheduler().rescheduleJob(trigger.getKey(), trigger);
}
else {
try {
if (jobDetail != null && !this.jobDetails.contains(jobDetail) &&
(this.overwriteExistingJobs || getScheduler().getJobDetail(jobDetail.getKey()) == null)) {
getScheduler().scheduleJob(jobDetail, trigger);
this.jobDetails.add(jobDetail);
}
else {
getScheduler().scheduleJob(trigger);
}
}
catch (ObjectAlreadyExistsException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Unexpectedly found existing trigger, assumably due to cluster race condition: " +
ex.getMessage() + " - can safely be ignored");
}
if (this.overwriteExistingJobs) {
getScheduler().rescheduleJob(trigger.getKey(), trigger);
}
}
}
return true;
}
@Override
public void storeCalendar(String name, Calendar calendar, boolean replaceExisting, boolean updateTriggers)
throws ObjectAlreadyExistsException, JobPersistenceException {
try {
realJobStore.storeCalendar(name, calendar, replaceExisting, updateTriggers);
} catch (RejoinException e) {
throw new JobPersistenceException("Storing calendar failed due to client rejoin", e);
}
}
@Override
public void storeJob(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException,
JobPersistenceException {
try {
realJobStore.storeJob(newJob, replaceExisting);
} catch (RejoinException e) {
throw new JobPersistenceException("Storing job failed due to client rejoin", e);
}
}
@Override
public void storeJobAndTrigger(JobDetail newJob, OperableTrigger newTrigger) throws ObjectAlreadyExistsException,
JobPersistenceException {
try {
realJobStore.storeJobAndTrigger(newJob, newTrigger);
} catch (RejoinException e) {
throw new JobPersistenceException("Storing job and trigger failed due to client rejoin", e);
}
}
@Override
public void storeTrigger(OperableTrigger newTrigger, boolean replaceExisting) throws ObjectAlreadyExistsException,
JobPersistenceException {
try {
realJobStore.storeTrigger(newTrigger, replaceExisting);
} catch (RejoinException e) {
throw new JobPersistenceException("Storing trigger failed due to client rejoin", e);
}
}
@Override
public void storeJobsAndTriggers(Map<JobDetail, Set<? extends Trigger>> arg0, boolean arg1)
throws ObjectAlreadyExistsException, JobPersistenceException {
try {
realJobStore.storeJobsAndTriggers(arg0, arg1);
} catch (RejoinException e) {
throw new JobPersistenceException("Store jobs and triggers failed due to client rejoin", e);
}
}
/**
* <p>
* Store the given <code>{@link org.quartz.Job}</code>.
* </p>
*
* @param newJob The <code>Job</code> to be stored.
* @param replaceExisting If <code>true</code>, any <code>Job</code> existing in the <code>JobStore</code> with the
* same name & group should be over-written.
* @throws ObjectAlreadyExistsException if a <code>Job</code> with the same name/group already exists, and
* replaceExisting is set to false.
*/
@Override
public void storeJob(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException,
JobPersistenceException {
JobDetail clone = (JobDetail) newJob.clone();
lock();
try {
// wrapper construction must be done in lock since serializer is unlocked
JobWrapper jw = wrapperFactory.createJobWrapper(clone);
if (jobFacade.containsKey(jw.getKey())) {
if (!replaceExisting) { throw new ObjectAlreadyExistsException(newJob); }
} else {
// get job group
Set<String> grpSet = toolkitDSHolder.getOrCreateJobsGroupMap(newJob.getKey().getGroup());
// add to jobs by group
grpSet.add(jw.getKey().getName());
if (!jobFacade.hasGroup(jw.getKey().getGroup())) {
jobFacade.addGroup(jw.getKey().getGroup());
}
}
// add/update jobs FQN map
jobFacade.put(jw.getKey(), jw);
} finally {
unlock();
}
}
/**
* <p>
* Store the given <code>{@link org.quartz.Calendar}</code>.
* </p>
*
* @param calendar The <code>Calendar</code> to be stored.
* @param replaceExisting If <code>true</code>, any <code>Calendar</code> existing in the <code>JobStore</code> with
* the same name & group should be over-written.
* @param updateTriggers If <code>true</code>, any <code>Trigger</code>s existing in the <code>JobStore</code> that
* reference an existing Calendar with the same name with have their next fire time re-computed with the new
* <code>Calendar</code>.
* @throws ObjectAlreadyExistsException if a <code>Calendar</code> with the same name already exists, and
* replaceExisting is set to false.
*/
@Override
public void storeCalendar(String name, Calendar calendar, boolean replaceExisting, boolean updateTriggers)
throws ObjectAlreadyExistsException, JobPersistenceException {
Calendar clone = (Calendar) calendar.clone();
lock();
try {
Calendar cal = calendarsByName.get(name);
if (cal != null && replaceExisting == false) {
throw new ObjectAlreadyExistsException("Calendar with name '" + name + "' already exists.");
} else if (cal != null) {
calendarsByName.remove(name);
}
Calendar cw = clone;
calendarsByName.putNoReturn(name, cw);
if (cal != null && updateTriggers) {
for (TriggerWrapper tw : triggerFacade.getTriggerWrappersForCalendar(name)) {
boolean removed = timeTriggers.remove(tw);
tw.updateWithNewCalendar(clone, getMisfireThreshold(), triggerFacade);
if (removed) {
timeTriggers.add(tw);
}
}
}
} finally {
unlock();
}
}
/**
* <p>
* Store the given <code>{@link org.quartz.Job}</code>.
* </p>
*
* @param newJob
* The <code>Job</code> to be stored.
* @param replaceExisting
* If <code>true</code>, any <code>Job</code> existing in the
* <code>JobStore</code> with the same name & group should be
* over-written.
* @throws ObjectAlreadyExistsException
* if a <code>Job</code> with the same name/group already
* exists, and replaceExisting is set to false.
*/
public void storeJob(JobDetail newJob,
boolean replaceExisting) throws ObjectAlreadyExistsException {
JobWrapper jw = new JobWrapper((JobDetail)newJob.clone());
boolean repl = false;
synchronized (lock) {
if (jobsByKey.get(jw.key) != null) {
if (!replaceExisting) {
throw new ObjectAlreadyExistsException(newJob);
}
repl = true;
}
if (!repl) {
// get job group
HashMap<JobKey, JobWrapper> grpMap = jobsByGroup.get(newJob.getKey().getGroup());
if (grpMap == null) {
grpMap = new HashMap<JobKey, JobWrapper>(100);
jobsByGroup.put(newJob.getKey().getGroup(), grpMap);
}
// add to jobs by group
grpMap.put(newJob.getKey(), jw);
// add to jobs by FQN map
jobsByKey.put(jw.key, jw);
} else {
// update job detail
JobWrapper orig = jobsByKey.get(jw.key);
orig.jobDetail = jw.jobDetail; // already cloned
}
}
}
@Override
public String scheduleJob(String xmlRequest) {
// StringBuffer servreponse = new StringBuffer();
JSONObject resp = new JSONObject();
Trigger trigger = null;
try {
Deserializer deserializer = DeserializerFactory.getDeserializer("application/xml");
trigger = (Trigger) deserializer.deserialize(xmlRequest, Trigger.class);
schedulerDAO.saveTrigger(trigger);
// all has been done
resp.put("Status", "OK");
// servreponse.append("<EXECUTION_OUTCOME outcome=\"perform\"/>");
} catch (Exception e) {
// something wrong
logger.error("Cannot save trigger", e);
try {
resp.put("Status", "NON OK");
JSONArray ja = new JSONArray();
if (e.getCause() instanceof ObjectAlreadyExistsException) {
ja.put("sbi.scheduler.schedulation.error.alreadyPresent");
} else {
ja.put("ERR SCK01");
}
resp.put("Errors", ja);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// servreponse.append("<EXECUTION_OUTCOME outcome=\"fault\"/>");
}
return resp.toString();
}
/**
* <p>
* Trigger the identified <code>{@link org.quartz.Job}</code> (execute it
* now) - with a non-volatile trigger.
* </p>
*/
public void triggerJob(SchedulingContext ctxt, String jobName,
String groupName, JobDataMap data) throws SchedulerException {
validateState();
if(groupName == null) {
groupName = Scheduler.DEFAULT_GROUP;
}
Trigger trig = new org.quartz.SimpleTrigger(newTriggerId(),
Scheduler.DEFAULT_MANUAL_TRIGGERS, jobName, groupName,
new Date(), null, 0, 0);
trig.setVolatility(false);
trig.computeFirstFireTime(null);
if(data != null) {
trig.setJobDataMap(data);
}
boolean collision = true;
while (collision) {
try {
resources.getJobStore().storeTrigger(ctxt, trig, false);
collision = false;
} catch (ObjectAlreadyExistsException oaee) {
trig.setName(newTriggerId());
}
}
notifySchedulerThread(trig.getNextFireTime().getTime());
notifySchedulerListenersSchduled(trig);
}
/**
* <p>
* Trigger the identified <code>{@link org.quartz.Job}</code> (execute it
* now) - with a volatile trigger.
* </p>
*/
public void triggerJobWithVolatileTrigger(SchedulingContext ctxt,
String jobName, String groupName, JobDataMap data) throws SchedulerException {
validateState();
if(groupName == null) {
groupName = Scheduler.DEFAULT_GROUP;
}
Trigger trig = new org.quartz.SimpleTrigger(newTriggerId(),
Scheduler.DEFAULT_MANUAL_TRIGGERS, jobName, groupName,
new Date(), null, 0, 0);
trig.setVolatility(true);
trig.computeFirstFireTime(null);
if(data != null) {
trig.setJobDataMap(data);
}
boolean collision = true;
while (collision) {
try {
resources.getJobStore().storeTrigger(ctxt, trig, false);
collision = false;
} catch (ObjectAlreadyExistsException oaee) {
trig.setName(newTriggerId());
}
}
notifySchedulerThread(trig.getNextFireTime().getTime());
notifySchedulerListenersSchduled(trig);
}
/**
* Add the given trigger to the Scheduler, if it doesn't already exist.
* Overwrites the trigger in any case if "overwriteExistingJobs" is set.
* @param trigger the trigger to add
* @return {@code true} if the trigger was actually added,
* {@code false} if it already existed before
* @see #setOverwriteExistingJobs
*/
private boolean addTriggerToScheduler(Trigger trigger) throws SchedulerException {
boolean triggerExists = (getScheduler().getTrigger(trigger.getKey()) != null);
if (triggerExists && !this.overwriteExistingJobs) {
return false;
}
// Check if the Trigger is aware of an associated JobDetail.
JobDetail jobDetail = (JobDetail) trigger.getJobDataMap().remove("jobDetail");
if (triggerExists) {
if (jobDetail != null && !this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) {
this.jobDetails.add(jobDetail);
}
getScheduler().rescheduleJob(trigger.getKey(), trigger);
}
else {
try {
if (jobDetail != null && !this.jobDetails.contains(jobDetail) &&
(this.overwriteExistingJobs || getScheduler().getJobDetail(jobDetail.getKey()) == null)) {
getScheduler().scheduleJob(jobDetail, trigger);
this.jobDetails.add(jobDetail);
}
else {
getScheduler().scheduleJob(trigger);
}
}
catch (ObjectAlreadyExistsException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Unexpectedly found existing trigger, assumably due to cluster race condition: " +
ex.getMessage() + " - can safely be ignored");
}
if (this.overwriteExistingJobs) {
getScheduler().rescheduleJob(trigger.getKey(), trigger);
}
}
}
return true;
}
private void storeTrigger(final ODatabaseDocumentTx db,
final OperableTrigger trigger,
final boolean replaceExisting)
throws JobPersistenceException
{
log.debug("Store trigger: trigger={}, replaceExisting={}", trigger, replaceExisting);
if (isClustered()) {
// associate trigger with the node that created it
trigger.getJobDataMap().put(NODE_ID, nodeAccess.getId());
}
TriggerEntity entity = triggerEntityAdapter.readByKey(db, trigger.getKey());
if (entity == null) {
// no existing entity, add new one
entity = new TriggerEntity(trigger, WAITING);
triggerEntityAdapter.addEntity(db, entity);
}
else {
// otherwise entity exists, maybe replace if allowed
if (replaceExisting) {
entity.setValue(trigger);
triggerEntityAdapter.editEntity(db, entity);
}
else {
throw new ObjectAlreadyExistsException(trigger);
}
}
}
@Test
public void testStoreTriggerReplacesTrigger() throws Exception {
String jobName = "StoreTriggerReplacesTrigger";
String jobGroup = "StoreTriggerReplacesTriggerGroup";
JobDetailImpl detail = new JobDetailImpl(jobName, jobGroup, MyJob.class);
jobStore.storeJob(detail, false);
String trName = "StoreTriggerReplacesTrigger";
String trGroup = "StoreTriggerReplacesTriggerGroup";
OperableTrigger tr = new SimpleTriggerImpl(trName, trGroup, new Date());
tr.setJobKey(new JobKey(jobName, jobGroup));
tr.setCalendarName(null);
jobStore.storeTrigger(tr, false);
assertEquals(tr, jobStore.retrieveTrigger(tr.getKey()));
try {
jobStore.storeTrigger(tr, false);
fail("an attempt to store duplicate trigger succeeded");
}
catch (ObjectAlreadyExistsException oaee) {
// expected
}
tr.setCalendarName("QQ");
jobStore.storeTrigger(tr, true); //fails here
assertEquals(tr, jobStore.retrieveTrigger(tr.getKey()));
assertEquals("StoreJob doesn't replace triggers", "QQ", jobStore.retrieveTrigger(tr.getKey()).getCalendarName());
}
@Test
@SuppressWarnings("deprecation")
public void testStoreTriggerReplacesTrigger() throws Exception {
String jobName = "StoreTriggerReplacesTrigger";
String jobGroup = "StoreTriggerReplacesTriggerGroup";
JobDetailImpl detail = new JobDetailImpl(jobName, jobGroup, MyJob.class);
fJobStore.storeJob(detail, false);
String trName = "StoreTriggerReplacesTrigger";
String trGroup = "StoreTriggerReplacesTriggerGroup";
OperableTrigger tr = new SimpleTriggerImpl(trName ,trGroup, new Date());
tr.setJobKey(new JobKey(jobName, jobGroup));
tr.setCalendarName(null);
fJobStore.storeTrigger(tr, false);
assertEquals(tr,fJobStore.retrieveTrigger(tr.getKey()));
try {
fJobStore.storeTrigger(tr, false);
fail("an attempt to store duplicate trigger succeeded");
} catch(ObjectAlreadyExistsException oaee) {
// expected
}
tr.setCalendarName("QQ");
fJobStore.storeTrigger(tr, true); //fails here
assertEquals(tr, fJobStore.retrieveTrigger(tr.getKey()));
assertEquals( "StoreJob doesn't replace triggers", "QQ", fJobStore.retrieveTrigger(tr.getKey()).getCalendarName());
}
/**
* Handle exceptions that result in a "conflict" status.
*/
@ExceptionHandler(value = {AlreadyExistsException.class, ObjectAlreadyExistsException.class, OptimisticLockException.class})
@ResponseStatus(HttpStatus.CONFLICT)
@ResponseBody
public ErrorInformation handleConflictException(Exception exception)
{
return getErrorInformation(HttpStatus.CONFLICT, exception);
}
/**
* Store calendar in redis.
*
* @param name the name
* @param calendar the calendar
* @param replaceExisting the replace existing
* @param updateTriggers the update triggers
* @param jedis thread-safe redis connection
* @throws ObjectAlreadyExistsException the object already exists exception
* @throws JobPersistenceException
*/
private void storeCalendar(String name, Calendar calendar,
boolean replaceExisting, boolean updateTriggers, Jedis jedis)
throws ObjectAlreadyExistsException, JobPersistenceException {
String calendarHashKey = createCalendarHashKey(name);
if (jedis.exists(calendarHashKey) && !replaceExisting)
throw new ObjectAlreadyExistsException(calendarHashKey + " already exists");
Gson gson = new Gson();
Map<String, String> calendarHash = new HashMap<>();
calendarHash.put(CALENDAR_CLASS, calendar.getClass().getName());
calendarHash.put(CALENDAR_SERIALIZED, gson.toJson(calendar));
jedis.hmset(calendarHashKey, calendarHash);
jedis.sadd(CALENDARS_SET, calendarHashKey);
if (updateTriggers) {
String calendarTriggersSetkey = createCalendarTriggersSetKey(name);
Set<String> triggerHasjKeys = jedis.smembers(calendarTriggersSetkey);
for (String triggerHashKey : triggerHasjKeys) {
OperableTrigger trigger = retrieveTrigger(new TriggerKey(triggerHashKey.split(":")[2], triggerHashKey.split(":")[1]), jedis);
long removed = jedis.zrem(RedisTriggerState.WAITING.getKey(), triggerHashKey);
trigger.updateWithNewCalendar(calendar, getMisfireThreshold());
if (removed == 1)
setTriggerState(RedisTriggerState.WAITING, (double)trigger.getNextFireTime().getTime(), triggerHashKey);
}
}
}
private void addTriggerToScheduler(CronTriggerImpl trigger) throws SchedulerException {
boolean triggerExists = (getScheduler().getTrigger(trigger.getKey()) != null);
if (!triggerExists) {
try {
getScheduler().scheduleJob(trigger);
} catch (ObjectAlreadyExistsException ex) {
getScheduler().rescheduleJob(trigger.getKey(),trigger);
}
} else {
getScheduler().rescheduleJob(trigger.getKey(),trigger);
}
}
private void addTriggerToScheduler(Trigger trigger) throws SchedulerException {
boolean triggerExists = (getScheduler().getTrigger(trigger.getKey()) != null);
if (!triggerExists) {
try {
getScheduler().scheduleJob(trigger);
} catch (ObjectAlreadyExistsException ex) {
getScheduler().rescheduleJob(trigger.getKey(),trigger);
}
} else {
getScheduler().rescheduleJob(trigger.getKey(),trigger);
}
}
/**
* <p>
* Store the given <code>{@link org.quartz.Trigger}</code>.
* </p>
*
* @param newTrigger The <code>Trigger</code> to be stored.
* @param replaceExisting If <code>true</code>, any <code>Trigger</code> existing in the <code>JobStore</code> with
* the same name & group should be over-written.
* @throws ObjectAlreadyExistsException if a <code>Trigger</code> with the same name/group already exists, and
* replaceExisting is set to false.
* @see #pauseTriggers(org.quartz.impl.matchers.GroupMatcher)
*/
@Override
public void storeTrigger(OperableTrigger newTrigger, boolean replaceExisting) throws JobPersistenceException {
OperableTrigger clone = (OperableTrigger) newTrigger.clone();
lock();
try {
JobDetail job = retrieveJob(newTrigger.getJobKey());
if (job == null) {
//
throw new JobPersistenceException("The job (" + newTrigger.getJobKey()
+ ") referenced by the trigger does not exist.");
}
// wrapper construction must be done in lock since serializer is unlocked
TriggerWrapper tw = wrapperFactory.createTriggerWrapper(clone, job.isConcurrentExectionDisallowed());
if (triggerFacade.containsKey(tw.getKey())) {
if (!replaceExisting) { throw new ObjectAlreadyExistsException(newTrigger); }
removeTrigger(newTrigger.getKey(), false);
}
// add to triggers by group
Set<String> grpSet = toolkitDSHolder.getOrCreateTriggersGroupMap(newTrigger.getKey().getGroup());
grpSet.add(newTrigger.getKey().getName());
if (!triggerFacade.hasGroup(newTrigger.getKey().getGroup())) {
triggerFacade.addGroup(newTrigger.getKey().getGroup());
}
if (triggerFacade.pausedGroupsContain(newTrigger.getKey().getGroup())
|| jobFacade.pausedGroupsContain(newTrigger.getJobKey().getGroup())) {
tw.setState(TriggerState.PAUSED, terracottaClientId, triggerFacade);
if (jobFacade.blockedJobsContain(tw.getJobKey())) {
tw.setState(TriggerState.PAUSED_BLOCKED, terracottaClientId, triggerFacade);
}
} else if (jobFacade.blockedJobsContain(tw.getJobKey())) {
tw.setState(TriggerState.BLOCKED, terracottaClientId, triggerFacade);
} else {
timeTriggers.add(tw);
}
// add to triggers by FQN map
triggerFacade.put(tw.getKey(), tw);
} finally {
unlock();
}
}
/**
* <p>
* Store the given <code>{@link org.quartz.Trigger}</code>.
* </p>
*
* @param newTrigger
* The <code>Trigger</code> to be stored.
* @param replaceExisting
* If <code>true</code>, any <code>Trigger</code> existing in
* the <code>JobStore</code> with the same name & group should
* be over-written.
* @throws ObjectAlreadyExistsException
* if a <code>Trigger</code> with the same name/group already
* exists, and replaceExisting is set to false.
*
* @see #pauseTriggers(org.quartz.impl.matchers.GroupMatcher)
*/
public void storeTrigger(OperableTrigger newTrigger,
boolean replaceExisting) throws JobPersistenceException {
TriggerWrapper tw = new TriggerWrapper((OperableTrigger)newTrigger.clone());
synchronized (lock) {
if (triggersByKey.get(tw.key) != null) {
if (!replaceExisting) {
throw new ObjectAlreadyExistsException(newTrigger);
}
removeTrigger(newTrigger.getKey(), false);
}
if (retrieveJob(newTrigger.getJobKey()) == null) {
throw new JobPersistenceException("The job ("
+ newTrigger.getJobKey()
+ ") referenced by the trigger does not exist.");
}
// add to triggers array
triggers.add(tw);
// add to triggers by group
HashMap<TriggerKey, TriggerWrapper> grpMap = triggersByGroup.get(newTrigger.getKey().getGroup());
if (grpMap == null) {
grpMap = new HashMap<TriggerKey, TriggerWrapper>(100);
triggersByGroup.put(newTrigger.getKey().getGroup(), grpMap);
}
grpMap.put(newTrigger.getKey(), tw);
// add to triggers by FQN map
triggersByKey.put(tw.key, tw);
if (pausedTriggerGroups.contains(newTrigger.getKey().getGroup())
|| pausedJobGroups.contains(newTrigger.getJobKey().getGroup())) {
tw.state = TriggerWrapper.STATE_PAUSED;
if (blockedJobs.contains(tw.jobKey)) {
tw.state = TriggerWrapper.STATE_PAUSED_BLOCKED;
}
} else if (blockedJobs.contains(tw.jobKey)) {
tw.state = TriggerWrapper.STATE_BLOCKED;
} else {
timeTriggers.add(tw);
}
}
}