how to run the quartz scheduler as soon as I started the server in JBOSS5.1.1 - jboss5.x

Currently I have added the quartz-1.8.6 and quartz-jboss-1.8.6 jars and quartz- service.xml file in jboss5.1.1 and i have added the quartz1.8.6 related jar files in the EAR application and I have return the code as follows:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
InitialContext ctx = new InitialContext();
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
JobDetail job = new JobDetail("job1", "group1", SimpleJob.class);
CronTrigger trigger = new CronTrigger("trigger1", "group1", "job1", "group1", "0/5 * * * * ?");
sched.addJob(job, true);
Date ft = sched.scheduleJob(trigger);
try
{
Thread.activeCount();
catch (Exception e)
{
}
sched.start();
}
catch (Exception exc){
exc.printStackTrace();
}
.....
}
but this code is running successfully once i logged in the link ...but i needed it to run the crontask once the server started

Related

Save on JDBC connections by using JdbcCursorItemReader or JdbcPagingItemReader

In the spring batch project, I used JdbcCursorItemReader to read data to process them in parallel. I can run the batch locally without any problem.
I also heard that JdbcPagingItemReader is recommended for parallel processing against JdbcCursorItemReader, as cursor reader will hold the connection too long while paging reader can release connection once the page size is reached.
I then switched to JdbcPagingItemReader in step2, but out of surprise, I got the exception below when running locally.
Caused by: java.sql.SQLTransientConnectionException: HikariPool-1 -
Connection is not available, request timed out after 300001ms.
However, it seems the above exception occurs in step1 before the paging reader in step2 is executed, and that is the only change made. Please shed some light on why the exception is thrown and if it is good practice to use paging reader instead of cursor in parallel processing. Much appreciated your help!
The code snippet is pasted below:
#Bean
#StepScope
public Flow createParallelSubFlow() {
List<Flow> subFlowList = new ArrayList<>();
List<Stream> streamList;
try {
streamList = dataSourceConfig.streamMapper().
getStreamListByStatus(Constants.PENDING_STATUS_CD);
} catch (Exception e) {
}
streamList.forEach(stream -> {
long id = stream.getStreamId();
String flowName = "stream" + id + "_flow";
Flow subFlow = new FlowBuilder<Flow>(flowName)
.start(step1(id))
.next(step2(id))
.end();
subFlowList.add(subFlow);
});
return new FlowBuilder<Flow>("splitFlow").split(new SimpleAsyncTaskExecutor())
.add(subFlowList.toArray(new Flow[0])).build();
}
public Step step1(long id) {
return stepBuilderFactory.get("step1")
.<Domain, Domain>chunk(100)
.reader(reader1(id))
.writer(writer1())
.build();
}
//#StepScope
//#Bean
public Step step2(long id) {
return stepBuilderFactory.get("step2")
.<Domain, Domain>chunk(100)
.reader(cursorReader2(id))
.processor(processor2)
.writer(writer2())
.build();
}
public JdbcCursorItemReader<Domain> cursorReader2(Long id) {
return new JdbcCursorItemReaderBuilder<Domain>()
.dataSource(dataSourceConfig.dataSource())
.name("cursorReader")
.sql(Constants.QUERY_SQL)
.preparedStatementSetter(new PreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setLong(1, id);
}})
.rowMapper(new RowMapper())
.build();
}
//Switch from cursorReader2 to pagingReader2 in step2
public JdbcPagingItemReader<Domain> pagingReader2(Long id) {
return new JdbcPagingItemReaderBuilder<Domain>()
.dataSource(dataSourceConfig.dataSource())
.name("pagingReader")
.queryProvider(queryProvider())
.parameterValues(parameterValues(id))
.rowMapper(new RowMapper())
.pageSize(100)
.build();
}
#Bean
public PagingQueryProvider queryProvider() {
SqlPagingQueryProviderFactoryBean providerFactory = new SqlPagingQueryProviderFactoryBean();
Map<String, Order> sortKeys = new HashMap<>(2);
sortKeys.put("ID", Order.ASCENDING);
providerFactory.setDataSource(dataSourceConfig.dataSource());
providerFactory.setSelectClause("SELECT Clause");
providerFactory.setFromClause("FROM Clause");
providerFactory.setWhereClause("WHERE Clause");
providerFactory.setSortKeys(sortKeys);
PagingQueryProvider pagingQueryProvider = null;
try {
pagingQueryProvider = providerFactory.getObject();
} catch (Exception e) {
logger.error("Failed to get PagingQueryProvider", e);
throw new RuntimeException("Failed to get PagingQueryProvider", e);
}
return pagingQueryProvider;
}
private Map<String, Object> parameterValues(Long id) {
Map<String, Object> parameterValues = new HashMap<>();
parameterValues.put("1", id);
return parameterValues;
}

How to get quartz scheduler end event

I have a following code where i have started a quartz scheduler
internal static IScheduler MyQuartzScheduler = null;
private static async void StartProcessing()
{
try
{
Logger.Info("Starting Quartz");
StdSchedulerFactory factory = new StdSchedulerFactory();
MyQuartzScheduler = await factory.GetScheduler();
await MyQuartzScheduler.Start();
QuartzScedulerMessage = String.Format("Quart Scheduler Started on {0}", DateTime.Now);
}
catch (Exception ex)
{
QuartzScedulerMessage = ex.Message;
Logger.Fatal(ex.Message, ex);
}
}
My scheduler is started and working fine. I were just curious if for any reason (like i have ado job store in my sql and db connectivity break) if scheduler crashes .Any how i can get scheduler ending or crashing event?
I think you should try Scheduler Listener in Quartz.NET here is the documentation ;
Scheduler Listener

how to run multiple jobs in quartz scheduler in struts

I implemented multiple jobs in quartz scheduler as a plugin in struts but only first job is running by using the tutorial from http://www.mkyong.com/struts/struts-quartz-scheduler-integration-example/
public class QuartzPlugin implements PlugIn {
private JobDetail job = null;
private Trigger trigger = null;
private Scheduler scheduler = null;
private static Class<QuartzPlugin> clazz = QuartzPlugin.class;
public static final String KEY_NAME = clazz.getName();
private static Logger logger = Logger.getLogger(clazz);
#Override
public void destroy() {
try {
String METHODNAME = "destroy";
logger.debug("entering " + KEY_NAME + " " + METHODNAME);
scheduler.shutdown();
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void init(ActionServlet servlet, ModuleConfig modConfig) throws ServletException {
String METHODNAME = "init";
logger.debug("entering " + KEY_NAME + " " + METHODNAME);
job = JobBuilder.newJob(SchedulerJob.class).withIdentity("anyJobName","group1").build();
try {
trigger = TriggerBuilder.newTrigger().withIdentity("anyTriggerName", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/30 * * * * ?")).build();
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
servlet.getServletContext().setAttribute(KEY_NAME, scheduler);
// define the job and tie it to our HelloJob class
JobDetail job2 = JobBuilder.newJob(HelloJob.class).withIdentity("job2", "group2").build();
// Trigger the job to run on the next round minute
Trigger trigger2 = TriggerBuilder.newTrigger().withIdentity("trigger2", "group2")
.withSchedule(CronScheduleBuilder.cronSchedule("15/45 * * * * ?")).build();
// Tell quartz to schedule the job using our trigger
scheduler.scheduleJob(job, trigger);
scheduler.scheduleJob(job2, trigger2);
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}

smartgwt spring servlet and uploading files

I've seen this question here before, but none of the solutions work for me.
I have a SmartGWT app with Spring MVC. This all works great, and I have working RESTful web-services.
I have a form to upload not only the file, but also some meta data as well.
There is an associated DataSource with this form:
private final String DEFAULT_FILE_UPLOAD_SERVICE_PATH = "upload";
private final String TARGET = "uploadTarget";
public FileUploadForm()
{
setEncoding(Encoding.MULTIPART);
setMethod(FormMethod.POST);
setAutoFetchData(false);
setDataSource(fileUploadDS);
setTitleOrientation(TitleOrientation.TOP);
setNumCols(1);
setColWidths("*");
uploadFileIdItem.setRequired(true);
uploadFileIdItem.setDefaultValue(0);
uploadFileIdItem.setVisible(false);
uploadFileIdItem.setShowTitle(false);
// ==========================================================================
fileUploadTypeSelectItem.setShowTitle(false);
fileUploadTypeSelectItem.setName(Constants.FILE_UPLOAD_UPLOADTYPE);
fileUploadTypeSelectItem.setPickListWidth(TEXT_SIZE);
fileUploadTypeSelectItem.setTitle(Constants.TITLE_FILE_UPLOAD_UPLOADTYPE);
fileUploadTypeSelectItem.setOptionDataSource(fileUploadTypeDS);
fileUploadTypeSelectItem.setRequired(true);
fileUploadTypeSelectItem.setDisplayField(Constants.FILE_UPLOAD_UPLOADTYPE_NAME);
fileUploadTypeSelectItem.setValueField(Constants.FILE_UPLOAD_UPLOADTYPE_ID);
fileUploadTypeSelectItem.setDataPath("fileUploadType/fileUploadTypeId");
// ==========================================================================
setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
ButtonItem uploadButton = new ButtonItem("Upload");
uploadButton.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler()
{
#Override
public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event)
{
submitForm();
}
});
FileItem uploadItem = new FileItem(Constants.FILENAME);
uploadItem.setTitle(Constants.FILENAME);
setFields(uploadFileIdItem, fileUploadTypeSelectItem, uploadItem, uploadButton);
}
So, I don't know if I need to use:
setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
or
setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
or
setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
None of these seem to work, I submit my data to upload the filename, and I constantly get the HTTP 404 error.
I did not define anything extra special in the web.xml file for servlets.
Instead, the springmvc-servlet contains:
<context:component-scan base-package="com.myself.products.app.server.controller" />
And the servlet is actually defined like:
#SuppressWarnings("serial")
#Controller
#RequestMapping("/upload")
public class FileUploadServlet extends HttpServlet
{
private final Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.process(request, response);
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// check that we have a file upload request
if (ServletFileUpload.isMultipartContent(request))
{
processFiles(request, response);
}
}
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/files/upload";
private File destinationDir;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
tmpDir = new File(((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).toString());
if (!tmpDir.isDirectory())
{
throw new ServletException(tmpDir.toString() + " is not a directory");
}
logger.debug("tmpDir: " + tmpDir.toString());
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory())
{
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}
private void processFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
// create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// set the size threshold, above which content will be stored on disk
factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
// set the temporary directory (this is where files that exceed the threshold will be stored)
factory.setRepository(tmpDir);
// create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// parse the request
List<?> items = upload.parseRequest(request);
// process the uploaded items
Iterator<?> itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
// write the uploaded file to the application's file staging area
File file = new File(destinationDir, item.getName());
item.write(file);
}
}
catch (FileUploadException e)
{
logger.error("Error encountered while parsing the request", e);
}
catch (Exception e)
{
logger.error("Error encountered while uploading file", e);
}
}
You've seen this code before along this web-site, and several others.
I'd like to submit the file, AND data if possible, but if not, then how can I submit the form, and then metadata for it?
Any help would be much appreciated.
Simple File Upload GWT Example:
Available here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FileUpload.html
For sending Metadata along with request, need to set the hidden field to panel:
import com.google.gwt.user.client.ui.Hidden;
Hidden hidden = new Hidden();
hidden.setName("json");
hidden.setVisible(false);
hidden.setValue("simpleMetadata:testData");
panel.add(hidden);
I will suggest you to seperate saving metadata from uploding a file and have 2 forms. This is what I'm doing and it is working for me:
uploadForm.setAction(GWT.getHostPageBaseURL() + "importServiceName");
uploadForm.setEncoding(Encoding.MULTIPART);
uploadForm.setTarget(TARGET);
uploadForm.setMethod(FormMethod.POST);
fileItem = new UploadItem("file");
fileItem.setTitle("File");
fileItem.setWidth(300);
NamedFrame frame = new NamedFrame(TARGET);
frame.setWidth("1");
frame.setHeight("1");
frame.setVisible(false);
uploadForm.setItems(fileItem);
I'm using NamedFrame to be able to fetch servlet response in gwt code, but this is different story. I'm defining servler manually in web.xml

Quartz scheduler in not running in war

I am using quartz scheduler in gwt web application.My application structure is like below.
I have two project.One is gwt web application client project(for ui part) & other is java project for server side call.(for database interaction).In client project I put a server project for reference.While running I create a war from client and add a jar of server project to war folder.
Now I used scheduler at server side for some task to auto complete.While running it locally (with out war) scheduler working properly.
But while running war at jboss server scheduler is not running.
My all scheduler related code and Quartz.jar is at server side.There is no any reference of Quartz in client side project.is this the problem???
Here is my code for scheduler
public class QuartzJob implements Job {
public void execute(JobExecutionContext jobExecutionContext)
throws JobExecutionException {
JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
ActivityTransactionSettingsMap map2 = (ActivityTransactionSettingsMap) map
.get("task");
if (map2.getAutoCompleteDate() != null) {
WorkFlowFacade facade = new WorkFlowFacade();
facade.completeAutoCompleteTask(map2);
Scheduler scheduler=(Scheduler) map.get("scheduler");
try {
scheduler.shutdown();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}
}
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
JobDataMap map2 = new JobDataMap();
map2.put("task", actsMap);
map2.put("scheduler", scheduler);
JobDetail job = newJob(QuartzJob.class).withIdentity("job"+String.valueOf(actsMap.getId()))
.usingJobData(map2).build();
Trigger trigger = newTrigger().withIdentity("trigger"+String.valueOf(actsMap.getId()))
.startAt(actsMap.getAutoCompleteDate()).build();
scheduler.scheduleJob(job, trigger);
Or do I need to shift my scheduler related project at client side only??
I am not getting how to solve this.
Please help me out
For the scheduler to run , there should be something to kick start it . I am not sure how the process is happening but you could write this scheduler in a servlet
public class MySchedulerServlet extends GenericServlet {
private static final long serialVersionUID = 1477091380142883153L;
/**
* Constant to represent property for the cron expression.
*/
private static final String CRON_EXPRESSION = "0 0 0 ? * SUN";
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
// The Quartz Scheduler
Scheduler scheduler = null;
try {
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
scheduler = schedulerFactory.getScheduler();
// Initiate JobDetail with job name, job group and
// executable job class
JobDetail jobDetail = new JobDetail("RetryJob", "RetryGroup", QuartzJob.class);
// Initiate CronTrigger with its name and group name
CronTrigger cronTrigger = new CronTrigger("cronTrigger",
"triggerGroup");
// setup CronExpression
CronExpression cexp = new CronExpression(CRON_EXPRESSION);
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);
// start the scheduler
scheduler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void service(ServletRequest serveletRequest,
ServletResponse servletResponse) throws ServletException, IOException {
}
}
and in your web.xml load sceduler on startup. This works for me.
<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>start-scheduler-on-load</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-name>MySchedulerServlet </servlet-name>
<servlet-class>com.servlet.MySchedulerServlet </servlet-class>
<load-on-startup>2</load-on-startup>
I used thread in this case.
public class AutoCompleteTaskThread extends Thread {
private ActivityTransactionSettingsMap taskMap;
public AutoCompleteTaskThread(ActivityTransactionSettingsMap map) {
this.taskMap = map;
}
#Override
public void run() {
try {
new AutoCompleteTaskScheduler().ScheduleJob(taskMap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
As below and in local machine it is working fine.but for jboss server it is not working.
I used an instance of AutoCompleteTaskThread class and called start method on this.
private void addAutoCompleteTask(ActivityTransactionSettingsMap newTask) {
AutoCompleteTaskThread thread = new AutoCompleteTaskThread(newTask);
thread.start();
}
Here for I started a thread for any new task for which I want to start new thread.