Alert shows empty message if called from task - task

Task<Void> task = new Task<Void>() {
public Void call() {
try {
// my task code
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
};
task.setOnSucceeded(event -> {
Platform.runLater(new Runnable() {
#Override
public void run() {
Alert alert = new Alert(AlertType.INFORMATION, "task success", ButtonType.OK);
alert.showAndWait();
}
});
});
In my above code i am trying to display alert message from success part of task.
I have deployed the application in a remote machine and accessing the same using remote desktop connection.
when i keep my remote desktop connection window minimised i get the alert message empty. (Yes i see the message when RDC window is open)
when i focus on parent container(stage) it refreshes and shows the correct message or just alt + tab few times also works. Tried various solutions to set modality, init stage, some vm args etc nothing seems to work.
any idea why this problem is? I understand task is a seperate thread and hence i have used platform.runlater? Have i done anything wrong? any alternative solutions?
Task runs on new thread as its performing a heavy operation.

Related

How to detect when Vaadin FileDownloader succeeds or fails

I have Vaadin 7 code to give the user an option to download a file:
Button btnDownloadResults = new Button("Download Results", FontAwesome.CLOUD_DOWNLOAD);
resource = new StreamResource(new MyStreamResource(), suggestedSaveAsFilename);
new FileDownloader(resource).extend(btnDownloadResults);
I would like to trigger code when the download has succeeded, or even if the download manages to start. Uses for this include closing a window, starting a progress spinner, or incrementing a download count.
Unlike the Vaadin Upload component, the FileDownloader does not have any listeners for finding out when a file download fails, succeeds, or starts.
Here is a simplified version of my StreamResouce subclass:
public class MyStreamResource implements StreamSource {
#Override
public InputStream getStream() {
String filename = /* code to determine the filename */;
try {
final File results = new File(FilenameUtils.normalize(filename));
return new FileInputStream(results);
} catch (FileNotFoundException fnfe) {
String errorMsg = "Cannot download results. Try again later, or contact your sysadmin.";
Utilities.showError(errorMsg);
return null;
} catch (Exception e) {
Utilities.logAndShowException(e);
return null;
}
}
}
Note that the getStream method returns before the user has even been prompted where to save the file (which they can choose to cancel.) So I can't trigger anything from inside that method.
One suggestion I got was to subclass the FileDownloader as follows:
FileDownloader fileDownloader = new FileDownloader(fileInputStream) {
private static final long serialVersionUID = -4584979099145066535L;
#Override
public boolean handleConnectorRequest(VaadinRequest request, VaadinResponse response, String path) throws IOException {
boolean result = super.handleConnectorRequest(request, response, path);
if (result) {
/* YOUR LOGIC GOES HERE */
}
return result;
}
} ;
Again, this fires too soon (and the boolean result is always true, even if my StreamSource returns null.)
Any suggestions?
After more research I believe the answer is that there is no simple way to get this information from the FileDownloader.
The difficulty appears to be a consequence of the way the FileDownloader is designed. From the FileDownloader docs:
"Download should be started directly when the user clicks e.g. a Button without going through a server-side click listener to avoid triggering security warnings in some browsers."
Because there is no round-trip back to the web server, there is no place to respond when the download fails, starts, or succeeds.
Some vague (and possibly bad) ideas for a workaround:
Have JS post some kind of asynchronous notification to the web
server, letting it know what happened. (Using JMS or Ajax?)
If there was some kind active process on the backend involved with transferring the file, it
would know when the transfer happened.
But the short answer seems to be there is no built-in way in Vaadin to do it.

how to perform two task in the backgroudworker process in asp.net MVC

I have to do two task parallelly in the backgroud worker process in the asp.net.
The following are the two task
Sent a email alert to support guys if any error event occurs in any of the server in a domain (All the time)
Sent the status report of error messages for all the servers in a domain at a time for every 4 hours or based on the user configuration.
I have already implemented the first task through the background worker process (
Now I want to implement second one and that fetch the data from the database for every 4 hours or user configured.
Please find the below are source code that i have used for implementation.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(DoWork);
worker.WorkerReportsProgress = false;
worker.WorkerSupportsCancellation = true;
worker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker.RunWorkerAsync();
}
private static void DoWork(object sender, DoWorkEventArgs e)
{
GetEmailAlertData objGetEmailAlertData = new GetEmailAlertData();
List<Email> lstEmaildetails = objGetEmailAlertData.GetEmailAlertDetails();
SentinelAlerter objSentinelAlerter = new SentinelAlerter();
foreach (Email objEmail in lstEmaildetails)
{
try
{
// I have implement first task
objAlerter.SendAlert(objEmail);
}
catch (Exception ex)
{
}
finally
{
}
}
}
Can anyone suggest how to implement the second task in the same background worker process.
I would recommend you to use Task Scheduler, its easy and will sort your issues out.

BlackBerry - How do I access a database (or create HTTP connection) in a background thread when the UI Application is not open

Overview:
Our application extends a UIApplication and has a SMS Listener class that is registered on boot. When a message is received that fits our criteria we process the message and then we want to save it to a local SQLite database as well as upload it to a Web Server. It is important that this happens as soon as possible after the SMS is received, even if the UI Application is not open at that stage.
Problem:
When the SMSListener Instance is running in the background, with no UIApplication instance active, and wants to access the SQLite database or tries to create a HTTP Connection a “No Application Instance” exception is thrown.
Desired outcome:
We want to process, save and upload all the messages from the SMSListener background thread even if the UIApplication is not active. Currently the SMSListener background thread would store the messages in the RuntimeStore; when the UI Application is started it reads the messages from the RuntimeStore and saves it to the database. This is not an optimal solution though, because the synchronisation with the Web Server would also then only happen when the UI Application is next opened. It is important that it rather syncs when the message is received.
Application Pseudo Code:
Main Class, checks for startup and creates a SMSListener instance or gets the instance from the RuntimeStore.
public class OurAppUi extends UiApplication {
public static void main(String[] args) {
if (args != null && args.length > 0 && args[0].endsWith("gui")) {
// Create a new instance of the application and make the currently
// running thread the application's event dispatch thread.
OurAppUi theApp = new OurAppUi();
theApp.enterEventDispatcher();
} else {
// Entered through the alternate application entry point
SmsListener.waitForSingleton();
}
}
}
The SMSListener Class listens for any incoming messages, makes use of the RuntimeStore Singleton Model. This is working as expected.
public class SmsListener implements javax.wireless.messaging.MessageListener {
public static SmsListener waitForSingleton() {
//Ensure this is a singleton instance.
//Open RuntimeStore and obtain the reference of BackgroundListener
RuntimeStore store = RuntimeStore.getRuntimeStore();
Object obj = store.get(ID_BACKGROUND_LISTENER);
//If obj is null, there is no current reference to BackgroundListener
//Start a new instance of BackgroundLIstener if one is not running
if(obj == null) {
store.put(ID_BACKGROUND_LISTENER, new SmsListener());
return (SmsListener)store.get(ID_BACKGROUND_LISTENER);
} else {
return(SmsListener)obj;
}
}
public void notifyIncomingMessage(MessageConnection conn) {
new Thread() {
MessageConnection connection;
Thread set (MessageConnection con) {
this.connection = con;
return (this);
}
public void run() {
try {
Message m = connection.receive();
String msg = null;
if (m instanceof TextMessage) {
TextMessage tm = (TextMessage)m;
msg = tm.getPayloadText();
}
// Process the SMS
SMSObject sms = processSMS(msg);
// Save to DataBase { Exception is Thrown Here }
SQLManager.getInstance().save(sms);
// Upload to Web Server { Exception is Thrown Here }
WebServer.upload(sms);
} catch(Exception error) {
}
}
}.set(conn).start();
}
}
When the SmsListener Instance wants to access the SQLite database or tries to create a HTTP Connection a “No Application Instance” exception is thrown.
public final class SQLManager {
private SQLManager() {
try {
db = OpenOrCreateDatabase();
} catch (MalformedURIException e) {
Debug.log(TAG, "Get connection: URI: " + e.getMessage());
} catch (ControlledAccessException e) {
Debug.log(TAG, "Get connection: Controlled Access: " + e.getMessage());
} catch (DatabasePathException e) {
Debug.log(TAG, "Get connection: Database Path: " + e.getMessage());
} catch (DatabaseIOException e) {
Debug.log(TAG, "Get connection: Database IO: " + e.getMessage());
} catch (Exception e) {
Debug.log(TAG, e);
}
}
public static synchronized SQLManager getInstance() {
if (instance == null) {
instance = new SQLManager();
}
return instance;
}
}
We’ve tried store the SQLite instances in the RuntimeStore, using the same Singleton Model as the SMSListener but received errors when the UI Application tried to access the stored DB Instance.
In general the way to handle this type of activity is to divide the application into two parts:
The user interactive parts that need the UI and need only be run when the user wants to interact with the application;
The background processing part that will store the data and communicate with the remote server.
The background processing should take place under the context of an extension of a net.rim.device.api.system.Application which probably should be a RuntimeStore based singleton. This portion should be started from your auto run code, register the listeners and remain active. There are some complexities involved in making sure the code executes in the right context. I have a blog post which may be helpful.

Automatically Stop Windows Service at Uninstall

When my service is installed I have a handler that starts the service after it has been installed.
private void InitializeComponent()
{
...
this.VDMServiceInstaller.AfterInstall += ServiceInstaller_AfterInstall;
}
private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController("MyService");
sc.Start();
}
I want to stop the service before it is uninstalled so I added an additional handler to InitializeComponent().
this.ServiceInstaller.BeforeUninstall += ServiceInstaller_BeforeUninstall;
and added the function:
private void ServiceInstaller_BeforeUninstall(object sender, InstallEventArgs e)
{
try
{
ServiceController sc = new ServiceController("MyService");
if (sc.CanStop)
{
sc.Stop();
sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
}
}
catch (Exception exception)
{}
}
But the service doesn't stop before uninstall. Am I using the ServiceController.Stop() function improperly?
Would something like below help you:
protected override void OnBeforeUninstall(IDictionary savedState)
{
ServiceController controller = new ServiceController("ServiceName");
try
{
if(controller.Status == ServiceControllerStatus.Running | controller.Status == ServiceControllerStatus.Paused)
{
controller.stop();
}
controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0,0,0,15));
controller.Close();
}
catch(Exception ex)
{
EventLog log = new EventLog();
log.WriteEntry("Service failed to stop");
}
finally
{
base.OnBeforeUninstall(savedState);
}
}
This is the window I tried to prevent:
I have tested all the overrides available, and none of them are executed before the dialog box prompting to close the applications appear.
Not even the class constructor is early enough.
My conclusion is that, as the installer projects are, you cannot stop the service via code, before the dialog box.
Since there are no other ways to have code executed in the project, I don't see any way to accomplish this.
I really really wish it was different, since I badly need this myself, but there just isn't any "hook" available in the installer project, that enters early enough to solve the problem.
My best suggestion, is to make two installers.
One that acts as a wrapper for the second, and on install just starts the second installer as normal.
But on uninstall, it stops the service first, then uninstalls the second.
But this is too much of a hack for my liking, so I have not explored this further.
I wanted to do something similar, and ended up using this code in my installer project to handle when the BeforeUninstall event was triggered:
private void SessionLoginMonitorInstaller_BeforeUninstall(object sender, InstallEventArgs e)
{
try
{
using (ServiceController sv = new ServiceController(SessionLoginMonitorInstaller.ServiceName))
{
if(sv.Status != ServiceControllerStatus.Stopped)
{
sv.Stop();
sv.WaitForStatus(ServiceControllerStatus.Stopped);
}
}
}
catch(Exception ex)
{
EventLog.WriteEntry("Logon Monitor Service", ex.Message, EventLogEntryType.Warning);
}
}
The custom actions section of the project also had an action to uninstall the primary output of my Windows Service project. This worked for me and has given me a clean uninstall every time I've tested it.

GWT-Platform + SmartGWT: Chained pop-up windows

I got a login window which, depending on the RPC response, will show me another Window. What I'm wondering is how to initialize the second Window. I tried onReset and onReveal methods but is like they are never triggered, In addition, when resetting values, using destroy() will kill my Window permanently. I ended up with the following solution, but I feel is not too efficient, can someone recommend me a way to do it?
public void onSuccess(LoginResult result) {
if(result.getResponse().equalsIgnoreCase("OK")){
getView().getUsernameField().setValue("");
getView().getPasswordField().setValue("");
getView().getWindow().hide();
memberWindow.setUsername(username);
memberWindow.loadAppointments(new Date());
((Window) memberWindow.getWidget()).show();
}else{
SC.say("Error", "Login failed because: " + result);
}
Try out something like this
#Override
public void onSuccess(LoginResult result) {
CurrentUser currentUser = new CurrentUser(getView().getUserName());
LoginAuthenticatedEvent.fire(eventBus, currentUser);
// notice the place manager call. The transitions between the pages are
// done in GWTP through PlaceManager.revealPlace(PlaceRequest) call.
PlaceRequest placeRequest = new PlaceRequest(NameTokens.mainPage);
getPlaceManager().revealPlace(placeRequest);
}
Check out
src\au\com\uptick\serendipity\client\presenter\SignInPagePresenter.java
from the Serendipity application a sample of login done with SmartGWT + GWTP :
http://code.google.com/p/crmdipity/downloads/detail?name=Serendipity-0.6.0.zip&can=2&q=

Resources