I have been working from an example I found, here's the link to the Git repo:
https://github.com/basakpie/vaadin8-spring-security-sample
It works great, it's just what I need, except for one thing: I need Server Push.
Here's what I've done so far:
added the Vaadin Push dependency
added the following lines to the start of the MainUI.init() method:
getPushConfiguration().setTransport(Transport.WEBSOCKET);
getPushConfiguration().setPushMode(PushMode.AUTOMATIC);
Added the following fields to the MainUI class:
Label time = new Label();
Timer timer;
Added the following method to the MainUI class:
private void updateTime() {
access(() -> time.setValue(String.format("The server-side time is %s", LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")))));
}
Finally, added the following to the end of the MainUI.init() method:
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
updateTime();
}
}, 1000L, 1000L);
It mostly works. I am able to see the current system time updating every second. But when I hit refresh in the browser, the application just hangs with the vaadin loading spinner. There are no error messages.
I have tried the following alternatives:
Adding the method
public void attach() {
getPushConfiguration().setTransport(Transport.WEBSOCKET);
getPushConfiguration().setPushMode(PushMode.AUTOMATIC);
}
and removing the getPushConfiguration lines from init()
This solves the hanging problem, but the push does not work - no errors, just the time is not displayed at all.
I also tried adding a #Push annotation to MainUI. This results in the same behaviour as before - freezing on refresh.
How can I fix this? Any suggestions would be welcome.
Try out the below procedure:
Add #Push to the MainUI.java file
#Push(transport = Transport.WEBSOCKET,value = PushMode.AUTOMATIC)
Instead of :
getPushConfiguration().setTransport(Transport.WEBSOCKET);
getPushConfiguration().setPushMode(PushMode.AUTOMATIC);
Add #PreDestroy to exit the timer when you navigate from the mainUI
#PreDestroy
void destroy() {
timer.cancel();
}
Find the complete revised code HERE
https://gist.github.com/cansoftinc/351452ee0e616d353519f147c4a961ba
I Had exactly the same problem and my solution to this was to implement the vaadin servlet. Check this for more information.
Related
I am trying to implement a feature of my Flutter application where the user will be reminded about something every 15 minutes through a notification banner. Since the interval of this reminder is pretty long, I intend to have a background service run in the background that would interface through some kind of an alarm manager that will execute the code to show the notification intermittently. Also, note that the interval of the reminders doesn't need to be exact.
My implementation plan is to use two Flutter packages in unison (flutter_local_notificationand android_alarm_manager). I cannot use flutter_local_notifications alone because the interval of a repeating notification is limited to one minute, one hour, one day, and so on whereas my app must have an interval of 15 minutes. With that, I completely removed the scheduling function from the flutter_local_notification package and gave that responsibility to android_alarm_manager.
I used these two of this packages by creating separate classes for each of them. The first class for the flutter_local_notifications package has something similar to a class from this article: https://itnext.io/local-notifications-in-flutter-6136235e1b51. On the other hand the class for android_alarm_manager has the following implementation in notification_alarm_manager.dart:
class NotificationAlarmManager {
NotificationAlarmManager() {
AndroidAlarmManager.initialize();
}
//I used interval in seconds here only for testing
void startNotifications(int intervalInSeconds) async {
await AndroidAlarmManager.periodic(
Duration(seconds: intervalInSeconds),
0,
_showRepeatingNotification,
);
print('Periodic alarm initialized');
}
static void _showRepeatingNotification() async {
print('Repeating notification will be shown');
var notification = LocalNotificationsPlugin();
await notification.showSingleNotification();
}
}
This class is instantiated from the main function with this implementation:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var alarmManager = NotificationAlarmManager();
runApp(CushionSensorApp(alarmManager));
}
The notifications are triggered to start from an the initState() function of the CushionSensorApp state as follows:
class _CushionSensorAppState extends State<CushionSensorApp> {
#override
void initState() {
...
this.widget.alarmManager.startNotifications(15);
}
...
}
The application builds correctly but whenever it's time for the android_alarm_manager to execute _showRepeatingNotification(), the primary error and a bunch of others will repeatedly be displayed instead:
MissingPluginException(No implementation found for method initialize on channel dexterous.com/flutter/local_notifications)
...
Yes, I already followed all the initial requirements for the android_alarm_manager (adding permissions, receivers). Also I had already added the custom Application.java file as an override and changing android:name to .Application. I even tried using the Kotlin file from this Github issue https://github.com/MaikuB/flutter_local_notifications/issues/238 but it still does not work.
Please refer to my repository for my details about my code (https://github.com/lewisbolaton/cushion_sensor_app).
EDIT:
I noticed that my question was linked to another. While our goals are similar, the other question's set up is different: they are creating all the GUI aspects of the program within the main class of their program, they are also setting the trigger event of the button press within the start method. Therefore the solution of using the "setOnAction(event->" coupled with Task works. It is a single class program, I was able to make the solution work if I created a new, single class program, this application does not work for me for my situation.
In my set up I am not running this event out of the main class, but out of the Controller class that is linked to my FXML and I have the event that triggers the method already defined. I did not post my entire Controller class as that seemed unnecessary. If there is a way to make the linked question's solution work for my different set up, or a link for guidance that would be stellar. I have looked into the "task" set up, taking from the linked question, but so far have not been able to get it to work successfully as pictured below:
#FXML
private void goForIt(ActionEvent event)
{
kickTheBaby();
}
private void kickTheBaby()
{
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
statusFld.setOnAction(event -> {statusFld.setText("Running");
Task task = new Task<Void>() {
#Override
public Void call()
{
(new Thread(new EmailCommunication("", currentTimestamp, "START"))).start();
(new Thread(new DataGathering2())).start();
return null;
}
};
task.setOnSucceeded(taskFinishEvent -> statusFld.setText(statusFld.getText()
+ "All done time to sleep..."));
new Thread(task).start();
});
}
I have a program in Java8 using FXML that downloads and parses data. I wish to make the program update the GUI TextField (called "statusFld" here) to say "Running" when I click the start button. Below is the method in the controller that should be responsible for this series of events.
#FXML
private void goForIt(ActionEvent event)
{
statusFld.setText("Running!");
java.util.Date now = calendar.getTime();
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(now.getTime());
(new Thread(new EmailCommunication("", currentTimestamp, "START"))).start();
(new Thread(new DataGathering2())).start();
}
However, when I attempt to run the program the GUI does not visually update and goes straight into the other two threads. So I attempted to utilize the "Platform.runLater()" methodology in one of the other threads by passing the status field to it as so:
Platform.runLater(() ->
{
statusFld.setText("Running!");
});
But after 20 minutes it had not given a visual update to the GUI. My guess is that this is probably due to the sheer amount of data processing that I am having it do, so who knows what "later" will actually be in this case.
My question is how can I be sure that the GUI visually updates before moving on to the other, very processing intense, threads?
Thank you!
In JME I try to use threading but when I run the program the function never starts.
I have a server socket who is listening to input from Netbeans.
Listener
while (isRunning) {
//Reads and prints the input
String receivedString = (String) in.readObject();
System.out.println(receivedString);
String[] parts = receivedString.split(";");
if(parts[0].equals("craneCon"))
{
final int containerId = Integer.parseInt(parts[1]);
m.enqueue(new Callable<Spatial>(){
public Spatial call() throws Exception{
m.removeContainersFromMaritime(containerId);
return null;
}
});
}
So in the main there is the function removeContainersFromMaritime
public void removeContainersFromMaritime(final int idContainer)
{
Node container = Maritime.listOfContainers.get(idContainer);
martime.detachChild(Maritime.listOfContainers.get(idContainer));
seagoingcrane.attachChild(Maritime.listOfContainers.get(idContainer));
container.setLocalTranslation(0,5,0);
System.out.println(Maritime.listOfContainers.get(0).getWorldTranslation().z);
}
The connection is alright but the method is never executed. How can I fix this?
jMonkeyEngine uses a swing-style threading model where there is a single render thread that does all the work. Any changes to the scene graph have to be done from that render thread.
To get into the render thread you can implement AppStates, Controls or you can enqueue Callables which are then executed on the render thread in a similar way to Swing's invokeLater.
The code snippet you posted looks about right, so assuming m is your running jME3 SimpleApplication then m.enqueue() will cause the enqueued callable to be executed next time around the render loop (i.e. at the start of the next frame).
If you are not seeing it executed then either:
Your application is not running
You created more than one application and enqueued it to the wrong one
The code is actually running and you just think it isn't.
Stepping through the code in the debugger and/or adding debug statements (for example breakpoint inside removeContainersFromMaritime to see if it is actually called should allow you to narrow this down.
I might be missing something but what is "m" in m.enqueue(...)?
I'm guessing it is an executor service of some sort and it's probably where the problem lies.
You could try instead:
new Thread() {public void run()
{
m.removeContainersFromMaritime(containerId);
}}.start();
It will at least show you if the problem is coming from "m" as an executor.
I'm working on a automatic logout class. After x minutes without actions I want to log out the user.
Everything is working, but I need a point in my application where to reset my timer.
I want to reset the timer with every click in my application. Is there a way to notice every click an throw an event? Maybe a LayeredPanel or GlassPanel?
I don't like the idea of resetting the timer by moving the mouse.
You can add some code to your EntryPoint:
Event.addNativePreviewHandler(new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getNativeEvent().getType().equals("click")) {
// reset your timer
}
}
});
In case the user clicks in your app, you'll get the chance to do something.
ImageView image = (ImageView) findViewById(R.id.imageview);
image.setImageResource(drawable.image1);
SystemClock.sleep(1000);
image.setImageResource(drawable.image2);
I am trying to change the image for a second, my code above doesn't work but not sure why?
Should I be using a thread? or does anyone have any better ideas?
EDIT
To clarify on the problem:
The image being displayed as "drawable.image2"
I want "drawable.image1" to be shown for one second then change to "drawable.image2".
EDIT2:
This code is used in the onClick. When a user clicks the image it needs to change for one second
I'd recommend using a TimerTask with a Timer. You can set it up like this:
protected void showDelayedImages() {
mImageView.setImageResource(resId1);
Timer timer = new Timer();
timer.schedule( new MyTimerTask(), 1000 );
}
private class MyTimerTask extends TimerTask {
#Override
public void run() {
runOnUiThread( new Runnable() {
#Override
public void run() {
mImageView.setImageResource(resId2);
}
} );
}
}
Thread.sleep(1000);
should do it. Although there are better ways too.
Use debug mode and set breakpoints on each call to setImageResource. Step through and see if each is getting called to see if your image is changing properly.
In real world cases, you probably want to change the image based on some user action, or for example change an icon while a thread is processing, then change it bad when complete. For this example check out AsyncTask.
use R.drawable.image1 instead of drawable.image1
It looks like you're performing the "switch" in an onCreate() method, the sleep will probably just make your Activity load slower since at this stage there isn't actually anything written to the page.
To have your image change you need to perform the switch on the UI thread and you need to perform it after the image has been inflated and added to the page.
Try adding this code in an "onClick" event.