Asynchronous method in seam always return null QuartzTriggerHandle ? - quartz-scheduler

QuartzTriggerHandle object that returned by Asynchronous method in Seam always 'null',
the job starts but cann't cancelled or paused.
In, seam forum i found the next example that should be work,but it doesn't work with me.
#Name("quartzObserver")
public class SCSQuartzObserver {
#In(create = true)
SCSQuartzTask quartzTask;
#SuppressWarnings("unused")
#Observer("org.jboss.seam.postInitialization")
public void observe() {
try {
Calendar cal = Calendar.getInstance();
cal.set(2040, Calendar.MAY, 10);
QuartzTriggerHandle handle = quartzTask.performTask(new Date(),
86400000l);
handle.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Name("quartzTask")
#AutoCreate
public class SCSQuartzTask {
#Asynchronous
public QuartzTriggerHandle performTask(#Expiration java.util.Date when,
#IntervalDuration long duration) {
// do stuff
QuartzTriggerHandle handle = new QuartzTriggerHandle("SCSQuartzTask");
return handle;
}
}
thnx for help.

You shouldn't create the QuartzTriggerHandle. Just do your work in the body of the performTask method, seam runtime will take care to return the QuartzTriggerHandle object. Something like this:
#Asynchronous
public QuartzTriggerHandle performTask(#Expiration java.util.Date when,
#IntervalDuration long duration) {
// do stuff
return null;
}
The QuartzTriggerHandle is serializable, you can keep it in a database table so you can later cancel the task.

Hi You must add something in component.xml
1-)async:quartz-dispatcher
2-)xsi:schemaLocation
http://jboss.com/products/seam/async
http://jboss.com/products/seam/async-2.2.xsd"
now it will work
you can find example Melih sakarya web site
http://www.melihsakarya.com/2011/09/seam-de-zamanli-isler-scheduling/

Related

Inject paramater into Spring Aspect Advice

I have a basic spring rest controller and have a company requirement which needs to log request and response in one combined log message. I planned on doing this with some simple aspect.
However the controller calls a service which in turn calls out to another third party api and there is requirement to include the time taken for this third party call in the log output from the controller mentioned above.
I am wondering if this can be achieved with aspects?
I guess it would need an #Around aspect for main controller and then another #Around for the downstream api call and some way to inject the result of the inner aspect to the advice or outer one. Not sure if this can be done?? Or perhaps a request scoped bean passed through aspects??
Thanks
How about a class Log
public class Log {
private long start;
private long end;
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
public long getEnd() {
return end;
}
public void setEnd(long end) {
this.end = end;
}
#Override
public String toString() {
return "Log [start=" + start + ", end=" + end + "]";
}
And pass the instance of this object through the api calls.
Say BeanOne.methodOne(Log,..) -> BeanTwo.methodTwo(Log,..) . BeanTwo.methodTwo() calls the external api and the time is recorded in Log instance.
and an advice as follows
#Around("execution(* methodOne(..)) && args(log)")
public void testAdviceBeanOne(ProceedingJoinPoint pjp,Log log) {
System.out.println("Before methodOne()");
try {
System.out.println(log);
pjp.proceed();
System.out.println(log);
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("After methodOne()");
}
Gives the output
Before methodOne()
Log [start=0, end=0]
Log [start=1572408716134, end=1572408716136]
After methodOne()
There could be a more elegant solution , still my two cents

Why Shiro's SubjectCallable need invoke restore method?

SubjectCallable's call method:
public V call() throws Exception {
try {
threadState.bind();
return doCall(this.callable);
} finally {
threadState.restore();
}
}
1.bind method is necsssary, but restore is why?
public void bind() {
SecurityManager securityManager = this.securityManager;
if ( securityManager == null ) {
//try just in case the constructor didn't find one at the time:
securityManager = ThreadContext.getSecurityManager();
}
this.originalResources = ThreadContext.getResources();
ThreadContext.remove();
ThreadContext.bind(this.subject);
if (securityManager != null) {
ThreadContext.bind(securityManager);
}
}
public void restore() {
ThreadContext.remove();
if (!CollectionUtils.isEmpty(this.originalResources)) {
ThreadContext.setResources(this.originalResources);
}
}
2.originalResources is use to do ? each time enter the AbstractShiroFilter will create a new subject and invoke it's execute method, the originalResources seems useless.
General thread health. You need to clean up resource in case the thread is re-used (very common). And it would help with garbage collection too.
Do you ever go hiking? Leave no trace ;)

Create observables using straight methods

I need to recollect some data calling to a method is connecting to a webservice.
problem: Imagine I need to update the content text of a label control according to this remote gathered information. Until all this data is recollected I'm not going to be able to show the label.
desired: I'd like to first show the label with a default text, and as I'm receiving this information I want to update the label content (please, don't take this description as a sucked code, I'm trying to brief my real situation).
I'd like to create an observable sequence of these methods. Nevertheless, these method have not the same signature. For example:
int GetInt() {
return service.GetInt();
}
string GetString() {
return service.GetString();
}
string GetString2 {
return service.GetString2();
}
These methods are not async.
Is it possible to create an observable sequence of these methods?
How could I create it?
Nevertheless, which's the best alternative to achieve my goal?
Creating custom observable sequences can be achieved with the Observable.Create. An example using your requirements is shown below:
private int GetInt()
{
Thread.Sleep(1000);
return 1;
}
private string GetString()
{
Thread.Sleep(1000);
return "Hello";
}
private string GetString2()
{
Thread.Sleep(2000);
return "World!";
}
private IObservable<string> RetrieveContent()
{
return Observable.Create<string>(
observer =>
{
observer.OnNext("Default Text");
int value = GetInt();
observer.OnNext($"Got value {value}. Getting string...");
string string1 = GetString();
observer.OnNext($"Got string {string1}. Getting second string...");
string string2 = GetString2();
observer.OnNext(string2);
observer.OnCompleted();
return Disposable.Empty;
}
);
}
Note how I have emulated network delay by introducing a Thread.Sleep call into each of the GetXXX methods. In order to ensure your UI doesn't hang when subscribing to this observable, you should subscribe as follows:
IDisposable subscription = RetrieveContent()
.SubscribeOn(TaskPoolScheduler.Default)
.ObserveOn(DispatcherScheduler.Current)
.Subscribe(text => Label = text);
This code uses the .SubscribeOn(TaskPoolScheduler.Default) extension method to use a TaskPool thread to start the observable sequence and will be blocked by the calls the Thread.Sleep but, as this is not the UI thread, your UI will remain responsive. Then, to ensure we update the UI on the UI thread, we use the ".ObserveOn(DispatcherScheduler.Current)" to invoke the updates onto the UI thread before setting the (data bound) Label property.
Hope this is what you were looking for, but leave a comment if not and I'll try to help further.
I would look at creating a wrapper class for your service to expose the values as separate observables.
So, start with a service interface:
public interface IService
{
int GetInt();
string GetString();
string GetString2();
}
...and then you write ServiceWrapper:
public class ServiceWrapper : IService
{
private IService service;
private Subject<int> subjectGetInt = new Subject<int>();
private Subject<string> subjectGetString = new Subject<string>();
private Subject<string> subjectGetString2 = new Subject<string>();
public ServiceWrapper(IService service)
{
this.service = service;
}
public int GetInt()
{
var value = service.GetInt();
this.subjectGetInt.OnNext(value);
return value;
}
public IObservable<int> GetInts()
{
return this.subjectGetInt.AsObservable();
}
public string GetString()
{
var value = service.GetString();
this.subjectGetString.OnNext(value);
return value;
}
public IObservable<string> GetStrings()
{
return this.subjectGetString.AsObservable();
}
public string GetString2()
{
var value = service.GetString2();
this.subjectGetString2.OnNext(value);
return value;
}
public IObservable<string> GetString2s()
{
return this.subjectGetString2.AsObservable();
}
}
Now, assuming that you current service is called Service, you would write this code to set things up:
IService service = new Service();
ServiceWrapper wrapped = new ServiceWrapper(service); // Still an `IService`
var subscription =
Observable
.Merge(
wrapped.GetInts().Select(x => x.ToString()),
wrapped.GetStrings(),
wrapped.GetString2s())
.Subscribe(x => label.Text = x);
IService wrappedService = wrapped;
Now pass wrappedService instead of service to your code. It's still calling the underlying service code so no need for a re-write, yet you still are getting the observables that you want.
This is effectively a gang of four decorator pattern.

How do I manage console output in a long running Eclipse plug-in?

I have written an Eclipse plugin that works. What happens, though, is that during the run, no console output is displayed. Only when the process is finished does the output show up in the console. Below is my handler, which appears as an extension point of type org.eclipse.ui.commands:
public class MyHandler extends AbstractHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
...
MessageConsoleStream out = myConsole.newMessageStream();
...
IConsoleView view = (IConsoleView) page.showView(id);
view.display(myConsole);
...
out.println("output that only shows up at the end");
myConsole.activate();
...
// Slow process
...
out.println("everything is done");
return null;
}
}
So while the process runs, nothing in the console. Then at the end, both output lines pop into view.
I'm obviously doing the console thing incorrectly, but I haven't found any good examples, nor has my experimentation proven very fruitful. Please advise.
You could consider using a ProgressMonitor (possibly with cancelation in case the user wants to abort), so that the user can see that there is something going on.
This worked:
public class Merge extends AbstractHandler {
private static MessageConsole myConsole = null;
private static ExecutionEvent event = null;
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Merge.event = event;
//same idea as original post and other examples where it makes new or finds existing
myConsole = makeConsole(Merge.event);
Job job = new Job("My Job Name"){
#Override
protected IStatus run(IProgressMonitor monitor){
...
if (blah) {
MessageConsoleStream out = myConsole.newMessageStream();
out.println("output show up right away");
...
// Slow process
...
out.println("everything is done");
} else {
MessageDialog.openInformation(HandlerUtil.getActiveShell(Merge.event), "Information", "Please select valid file");
}
monitor.done();
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
return null;
}
...
}
Maybe you can call out.flush() after every out.print...

How can I correctly update a progress bar for an operation of unknown duration within an Eclipse wizard?

I have implemented a wizard for my Eclipse plug-in, showing several pages. One of these pages needs some lengthy initialization, that means it consists of a SWT table, which needs to be populated by information coming from an external source. This source needs to be activated first (one single method call that returns after a couple of seconds - I can not know in advance how long it will take exactly), before it can be used as input for for the table viewer. This initialization is currently done by the table model provider when it needs to access the external source for the first time.
Therefore, when I enter the wizard page, I would like to show a dummy progress bar that just counts up for a while. My approach was the following, but unfortunately does not work at all:
private void initViewer() {
IRunnableWithProgress runnable = new IRunnableWithProgress() { // needed to embed long running operation into the wizard page
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
SubMonitor progress = SubMonitor.convert(monitor);
Thread thread = new Thread() {
#Override
public void run() {
Display.getDefault().syncExec(new Runnable() {
public void run() {
viewer.setInput(ResourcesPlugin.getWorkspace().getRoot()); // this will make the table provider initialize the external source.
}
});
}
};
thread.start();
while(thread.isAlive()) {
progress.setWorkRemaining(10000);
progress.worked(1);
}
progress.done();
}
};
try {
getContainer().run(false, false, runnable);
} catch(Exception e) {
throw new Exception("Could not access data store", e);
}
}
This method gets then invoked when the wizard page's setVisible()-method is called and should, after a couple of seconds, set the viewer's input. This, however, never happens, because the inner-most run()-method never gets executed.
Any hints on how to deal with long-running (where an exact estimate is not available) initializations in Eclipse wizards would be very appreciated!
I have given below a simple example on how to use IRunnableWithProgress along with a ProgressMonitorDialog to perform a task of unknown quantity. To start with, have an implementation to IRunnableWithProgress from where the actual task is performed. This implementation could be an inner class.
public class MyRunnableWithProgress implements IRunnableWithProgress {
private String _fileName;
public MyRunnableWithProgress(String fileName) {
_fileName = fileName;
}
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
int totalUnitsOfWork = IProgressMonitor.UNKNOWN;
monitor.beginTask("Performing read. Please wait...", totalUnitsOfWork);
performRead(_fileName, monitor); // This only performs the tasks
monitor.done();
}
}
Now, a generic implementation to ProgressMonitorDialog can be created as below which could be used for other places where a progress monitor dialog is required.
public class MyProgressMonitorDialog extends ProgressMonitorDialog {
private boolean cancellable;
public MyProgressMonitorDialog(Shell parent, boolean cancellable) {
super(parent);
this.cancellable = cancellable;
}
#Override
public Composite createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
setCancelable(cancellable);
return container;
}
}
Having got the required implementation, the task can be invoked as below to get it processed with a progress dialog.
boolean cancellable = false;
IRunnableWithProgress myRunnable = new MyRunnableWithProgress(receivedFileName);
ProgressMonitorDialog progressMonitorDialog = new MyProgressMonitorDialog(getShell(), cancellable);
try {
progressMonitorDialog.run(true, true, myRunnable);
} catch (InvocationTargetException e) {
// Catch in your best way
throw new RuntimeException(e);
} catch (InterruptedException e) {
//Catch in your best way
Thread.currentThread().interrupt();
}
Hope this helps!
I assume the reason why it's "not working" for you is that the preparation of input is done in UI thread meaning that the progress bar cannot be updated. A better approach is to prepare input in advance and only set input to viewer after that.