use of org.quartz.SchedulerException in project openhab1-addons by openhab.
the class SonosBinding method execute.
@Override
protected void execute() {
if (isProperlyConfigured()) {
if (!bindingStarted) {
// This will create necessary network resources for UPnP right away
upnpService = new UpnpServiceImpl(new SonosUpnpServiceConfiguration(), listener);
try {
Iterator<SonosZonePlayer> it = sonosZonePlayerCache.iterator();
while (it.hasNext()) {
SonosZonePlayer aPlayer = it.next();
if (aPlayer.getDevice() == null) {
logger.info("Querying the network for a predefined Sonos device with UDN {}", aPlayer.getUdn());
upnpService.getControlPoint().search(new UDNHeader(aPlayer.getUdn()));
}
}
logger.info("Querying the network for any other Sonos device");
final UDAServiceType udaType = new UDAServiceType("AVTransport");
upnpService.getControlPoint().search(new UDAServiceTypeHeader(udaType));
} catch (Exception e) {
logger.warn("An exception occurred while searching the network for Sonos devices: ", e.getMessage());
}
bindingStarted = true;
}
Scheduler sched = null;
try {
sched = StdSchedulerFactory.getDefaultScheduler();
} catch (SchedulerException e) {
logger.error("An exception occurred while getting a reference to the Quartz Scheduler");
}
// Cycle through the Items and setup sonos zone players if required
for (SonosBindingProvider provider : providers) {
for (String itemName : provider.getItemNames()) {
for (String sonosID : provider.getSonosID(itemName)) {
if (!sonosZonePlayerCache.contains(sonosID)) {
// the device is not yet discovered on the network or not defined in the .cfg
// Verify that the sonosID has the format of a valid UDN
Pattern SONOS_UDN_PATTERN = Pattern.compile("RINCON_(\\w{17})");
Matcher matcher = SONOS_UDN_PATTERN.matcher(sonosID);
if (matcher.matches()) {
// Add device to the cached Configs
SonosZonePlayer thePlayer = new SonosZonePlayer(sonosID, self);
thePlayer.setUdn(new UDN(sonosID));
sonosZonePlayerCache.add(thePlayer);
// Query the network for this device
logger.info("Querying the network for a predefined Sonos device with UDN '{}'", thePlayer.getUdn());
upnpService.getControlPoint().search(new UDNHeader(thePlayer.getUdn()));
}
}
}
}
}
// Cycle through the item binding configuration that define polling criteria
for (SonosCommandType sonosCommandType : SonosCommandType.getPolling()) {
for (SonosBindingProvider provider : providers) {
for (String itemName : provider.getItemNames(sonosCommandType.getSonosCommand())) {
for (Command aCommand : provider.getCommands(itemName, sonosCommandType.getSonosCommand())) {
// We are dealing with a valid device
SonosZonePlayer thePlayer = sonosZonePlayerCache.getById(provider.getSonosID(itemName, aCommand));
if (thePlayer != null) {
RemoteDevice theDevice = thePlayer.getDevice();
// Not all Sonos devices have the same capabilities
if (theDevice != null) {
if (theDevice.findService(new UDAServiceId(sonosCommandType.getService())) != null) {
boolean jobExists = false;
// enumerate each job group
try {
for (String group : sched.getJobGroupNames()) {
// enumerate each job in group
for (JobKey jobKey : sched.getJobKeys(jobGroupEquals(group))) {
if (jobKey.getName().equals(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString())) {
jobExists = true;
break;
}
}
}
} catch (SchedulerException e1) {
logger.error("An exception occurred while quering the Quartz Scheduler ({})", e1.getMessage());
}
if (!jobExists) {
// set up the Quartz jobs
JobDataMap map = new JobDataMap();
map.put("Player", thePlayer);
JobDetail job = newJob(sonosCommandType.getJobClass()).withIdentity(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString(), "Sonos-" + provider.toString()).usingJobData(map).build();
Trigger trigger = newTrigger().withIdentity(provider.getSonosID(itemName, aCommand) + "-" + sonosCommandType.getJobClass().toString(), "Sonos-" + provider.toString()).startNow().withSchedule(simpleSchedule().repeatForever().withIntervalInMilliseconds(pollingPeriod)).build();
try {
sched.scheduleJob(job, trigger);
} catch (SchedulerException e) {
logger.error("An exception occurred while scheduling a Quartz Job ({})", e.getMessage());
}
}
}
}
}
}
}
}
}
}
}
use of org.quartz.SchedulerException in project OpenClinica by OpenClinica.
the class XsltTransformJob method sendErrorEmail.
private void sendErrorEmail(String message, JobExecutionContext context, String target) {
String subject = "Warning: " + message;
String emailBody = "An exception was thrown while running an extract job on your server, please see the logs for more details.";
try {
ApplicationContext appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
mailSender = (OpenClinicaMailSender) appContext.getBean("openClinicaMailSender");
mailSender.sendEmail(target, EmailEngine.getAdminEmail(), subject, emailBody, false);
logger.info("sending an email to " + target + " from " + EmailEngine.getAdminEmail());
} catch (SchedulerException se) {
logger.warn("Error sending email", se);
} catch (OpenClinicaSystemException ose) {
logger.warn("Error sending email", ose);
}
}
use of org.quartz.SchedulerException in project OpenClinica by OpenClinica.
the class CreateJobExportServlet method processRequest.
@Override
protected void processRequest() throws Exception {
// TODO multi stage servlet which will create export jobs
// will accept, create, and return the ViewJob servlet
FormProcessor fp = new FormProcessor(request);
TriggerService triggerService = new TriggerService();
scheduler = getScheduler();
String action = fp.getString("action");
ExtractUtils extractUtils = new ExtractUtils();
if (StringUtil.isBlank(action)) {
// set up list of data sets
// select by ... active study
setUpServlet();
forwardPage(Page.CREATE_JOB_EXPORT);
} else if ("confirmall".equalsIgnoreCase(action)) {
// collect form information
Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals("DEFAULT"));
String[] triggerNames = triggerKeys.stream().toArray(String[]::new);
HashMap errors = validateForm(fp, request, triggerNames, "");
if (!errors.isEmpty()) {
// set errors to request
request.setAttribute("formMessages", errors);
logger.info("has validation errors in the first section");
logger.info("errors found: " + errors.toString());
setUpServlet();
forwardPage(Page.CREATE_JOB_EXPORT);
} else {
logger.info("found no validation errors, continuing");
StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
DatasetDAO datasetDao = new DatasetDAO(sm.getDataSource());
UserAccountBean userBean = (UserAccountBean) request.getSession().getAttribute("userBean");
CoreResources cr = new CoreResources();
int datasetId = fp.getInt(DATASET_ID);
String period = fp.getString(PERIOD);
String email = fp.getString(EMAIL);
String jobName = fp.getString(JOB_NAME);
String jobDesc = fp.getString(JOB_DESC);
Date startDateTime = fp.getDateTime(DATE_START_JOB);
Integer exportFormatId = fp.getInt(FORMAT_ID);
ExtractPropertyBean epBean = cr.findExtractPropertyBeanById(exportFormatId, "" + datasetId);
DatasetBean dsBean = (DatasetBean) datasetDao.findByPK(new Integer(datasetId).intValue());
// set the job in motion
String[] files = epBean.getFileName();
String exportFileName;
int fileSize = files.length;
int cnt = 0;
dsBean.setName(dsBean.getName().replaceAll(" ", "_"));
String[] exportFiles = epBean.getExportFileName();
String pattern = "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator + "HHmmssSSS" + File.separator;
SimpleDateFormat sdfDir = new SimpleDateFormat(pattern);
int i = 0;
String[] temp = new String[exportFiles.length];
//JN: The following logic is for comma separated variables, to avoid the second file be treated as a old file and deleted.
String datasetFilePath = SQLInitServlet.getField("filePath") + "datasets";
while (i < exportFiles.length) {
temp[i] = extractUtils.resolveVars(exportFiles[i], dsBean, sdfDir, datasetFilePath);
i++;
}
epBean.setDoNotDelFiles(temp);
epBean.setExportFileName(temp);
XsltTriggerService xsltService = new XsltTriggerService();
String generalFileDir = SQLInitServlet.getField("filePath");
generalFileDir = generalFileDir + "datasets" + File.separator + dsBean.getId() + File.separator + sdfDir.format(new java.util.Date());
exportFileName = epBean.getExportFileName()[cnt];
// need to set the dataset path here, tbh
// next, can already run jobs, translations, and then add a message to be notified later
//JN all the properties need to have the variables...
String xsltPath = SQLInitServlet.getField("filePath") + "xslt" + File.separator + files[cnt];
String endFilePath = epBean.getFileLocation();
endFilePath = extractUtils.getEndFilePath(endFilePath, dsBean, sdfDir, datasetFilePath);
// exportFileName = resolveVars(exportFileName,dsBean,sdfDir);
if (epBean.getPostProcExportName() != null) {
//String preProcExportPathName = getEndFilePath(epBean.getPostProcExportName(),dsBean,sdfDir);
String preProcExportPathName = extractUtils.resolveVars(epBean.getPostProcExportName(), dsBean, sdfDir, datasetFilePath);
epBean.setPostProcExportName(preProcExportPathName);
}
if (epBean.getPostProcLocation() != null) {
String prePocLoc = extractUtils.getEndFilePath(epBean.getPostProcLocation(), dsBean, sdfDir, datasetFilePath);
epBean.setPostProcLocation(prePocLoc);
}
extractUtils.setAllProps(epBean, dsBean, sdfDir, datasetFilePath);
SimpleTrigger trigger = null;
trigger = xsltService.generateXsltTrigger(scheduler, xsltPath, // xml_file_path
generalFileDir, endFilePath + File.separator, exportFileName, dsBean.getId(), epBean, userBean, LocaleResolver.getLocale(request).getLanguage(), cnt, SQLInitServlet.getField("filePath") + "xslt", xsltService.getTriggerGroupNameForExportJobs());
//Updating the original trigger with user given inputs
trigger.getTriggerBuilder().withSchedule(simpleSchedule().withRepeatCount(64000).withIntervalInSeconds(new Integer(period).intValue()).withMisfireHandlingInstructionNextWithExistingCount()).startAt(startDateTime).forJob(jobName).withDescription(jobDesc);
trigger.getJobDataMap().put(XsltTriggerService.EMAIL, email);
trigger.getJobDataMap().put(XsltTriggerService.PERIOD, period);
trigger.getJobDataMap().put(XsltTriggerService.EXPORT_FORMAT, epBean.getFiledescription());
trigger.getJobDataMap().put(XsltTriggerService.EXPORT_FORMAT_ID, exportFormatId);
trigger.getJobDataMap().put(XsltTriggerService.JOB_NAME, jobName);
trigger.getJobDataMap().put("job_type", "exportJob");
JobDetailFactoryBean JobDetailFactoryBean = new JobDetailFactoryBean();
JobDetailFactoryBean.setGroup(xsltService.getTriggerGroupNameForExportJobs());
JobDetailFactoryBean.setName(trigger.getKey().getName());
JobDetailFactoryBean.setJobClass(org.akaza.openclinica.job.XsltStatefulJob.class);
JobDetailFactoryBean.setJobDataMap(trigger.getJobDataMap());
// need durability?
JobDetailFactoryBean.setDurability(true);
// set to the scheduler
try {
Date dateStart = scheduler.scheduleJob(JobDetailFactoryBean.getObject(), trigger);
logger.info("== found job date: " + dateStart.toString());
// set a success message here
} catch (SchedulerException se) {
se.printStackTrace();
setUpServlet();
addPageMessage("Error creating Job.");
forwardPage(Page.VIEW_JOB_SERVLET);
return;
}
setUpServlet();
addPageMessage("You have successfully created a new job: " + jobName + " which is now set to run at the time you specified.");
forwardPage(Page.VIEW_JOB_SERVLET);
}
} else {
forwardPage(Page.ADMIN_SYSTEM);
// forward to form
// should we even get to this part?
}
}
use of org.quartz.SchedulerException in project OpenClinica by OpenClinica.
the class CreateJobImportServlet method processRequest.
@Override
protected void processRequest() throws Exception {
// TODO multi stage servlet to generate import jobs
// validate form, create job and return to view jobs servlet
FormProcessor fp = new FormProcessor(request);
TriggerService triggerService = new TriggerService();
scheduler = getScheduler();
String action = fp.getString("action");
if (StringUtil.isBlank(action)) {
// set up list of data sets
// select by ... active study
setUpServlet();
forwardPage(Page.CREATE_JOB_IMPORT);
} else if ("confirmall".equalsIgnoreCase(action)) {
// collect form information
Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(IMPORT_TRIGGER));
String[] triggerNames = triggerKeys.stream().toArray(String[]::new);
HashMap errors = triggerService.validateImportJobForm(fp, request, triggerNames);
if (!errors.isEmpty()) {
// set errors to request
request.setAttribute("formMessages", errors);
logger.debug("has validation errors in the first section" + errors.toString());
setUpServlet();
forwardPage(Page.CREATE_JOB_IMPORT);
} else {
logger.info("found no validation errors, continuing");
int studyId = fp.getInt(STUDY_ID);
StudyDAO studyDAO = new StudyDAO(sm.getDataSource());
StudyBean studyBean = (StudyBean) studyDAO.findByPK(studyId);
SimpleTrigger trigger = triggerService.generateImportTrigger(fp, sm.getUserBean(), studyBean, LocaleResolver.getLocale(request).getLanguage());
// SimpleTrigger trigger = new SimpleTrigger();
JobDetailFactoryBean JobDetailFactoryBean = new JobDetailFactoryBean();
JobDetailFactoryBean.setGroup(IMPORT_TRIGGER);
JobDetailFactoryBean.setName(trigger.getKey().getName());
JobDetailFactoryBean.setJobClass(org.akaza.openclinica.web.job.ImportStatefulJob.class);
JobDetailFactoryBean.setJobDataMap(trigger.getJobDataMap());
// need durability?
JobDetailFactoryBean.setDurability(true);
// set to the scheduler
try {
Date dateStart = scheduler.scheduleJob(JobDetailFactoryBean.getObject(), trigger);
logger.debug("== found job date: " + dateStart.toString());
// set a success message here
addPageMessage("You have successfully created a new job: " + trigger.getKey().getName() + " which is now set to run at the time you specified.");
forwardPage(Page.VIEW_IMPORT_JOB_SERVLET);
} catch (SchedulerException se) {
se.printStackTrace();
// set a message here with the exception message
setUpServlet();
addPageMessage("There was an unspecified error with your creation, please contact an administrator.");
forwardPage(Page.CREATE_JOB_IMPORT);
}
}
} else {
forwardPage(Page.ADMIN_SYSTEM);
// forward to form
// should we even get to this part?
}
}
use of org.quartz.SchedulerException in project OpenClinica by OpenClinica.
the class XsltTransformJob method postSuccessMessage.
private void postSuccessMessage(String message, JobExecutionContext context) {
String SCHEDULER = "schedulerFactoryBean";
try {
ApplicationContext appContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext");
StdScheduler scheduler = (StdScheduler) appContext.getBean(SCHEDULER);
JobDetail jobDetail = context.getJobDetail();
JobDataMap dataMap = jobDetail.getJobDataMap();
dataMap.put("successMsg", message);
jobDetail.getJobBuilder().usingJobData(dataMap);
// replace the job with the extra data
scheduler.addJob(jobDetail, true);
} catch (SchedulerException e) {
throw new IllegalStateException("Error processing post success message", e);
}
}
Aggregations