For a school project, I am programming a little Visualization for a PLC. Therefore I have a mySQL Database which has all the Information. Currently, when I click on a Button the program connects to the Database and gets it Information in an ArrayList. Then it checks the information in the ArrayList and puts Data in a ListView.
The problem is, that I want to let the program do that in a Service. As I said the GUI depends on the ArrayList. And I can't change the GUI in the service because then this Exception appears
Sep 02, 2016 9:19:02 PM javafx.concurrent.Service lambda$static$488
WARNING: Uncaught throwable in javafx concurrent thread pool
java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-4
at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source)
at javafx.scene.Parent$2.onProposedChange(Unknown Source)
at com.sun.javafx.collections.VetoableListDecorator.setAll(Unknown Source)
at com.sun.javafx.collections.VetoableListDecorator.setAll(Unknown Source)
at com.sun.javafx.scene.control.skin.LabeledSkinBase.updateChildren(Unknown Source)
at com.sun.javafx.scene.control.skin.LabeledSkinBase.handleControlPropertyChanged(Unknown Source)
at com.sun.javafx.scene.control.skin.LabelSkin.handleControlPropertyChanged(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase.lambda$registerChangeListener$61(Unknown Source)
at com.sun.javafx.scene.control.MultiplePropertyChangeListenerHandler$1.changed(Unknown Source)
at javafx.beans.value.WeakChangeListener.changed(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(Unknown Source)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(Unknown Source)
at javafx.beans.property.StringPropertyBase.fireValueChangedEvent(Unknown Source)
at javafx.beans.property.StringPropertyBase.markInvalid(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringPropertyBase.set(Unknown Source)
at javafx.beans.property.StringProperty.setValue(Unknown Source)
at javafx.scene.control.Labeled.setText(Unknown Source)
at application.Controller$1$1.call(Controller.java:290)
at application.Controller$1$1.call(Controller.java:1)
at javafx.concurrent.Task$TaskCallable.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at javafx.concurrent.Service.lambda$null$493(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javafx.concurrent.Service.lambda$executeTask$494(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
My first Idea was to extract only the SQL stuff in the Service and then get the Data via the Method
service.getValue();
But the problem with this is that I don't know when the Service is finished to get the Data, because currently, the data is null.
Basically, you want to run some process and return some value,
Of course Service nails it. This is how I go about my case and it works perfectly.
Service process = new Service() {
#Override
protected Task createTask() {
return new Task() {
#Override
protected ObjectX call() throws Exception {
updateMessage("Some message that may change with execution");
updateProgress( workDone, totalWork );
return ObjectX;
}
};
}
};
process.setOnSucceeded( e -> {
ObjectX processValue = (ObjectX)process.getValue();
// TODO, . . .
// You can modify any GUI element from here...
// ...with the values you got from the service
});
process.start();
THINGS TO NOTE
inner method protected ObjectX call() can return any type of object. Just make sure its an object and not a primitive type. You can go as far as populate some GUI elements inside this process and return it as an object, eg. protected VBox call() . . . . return my_vbox;
ObjectX processValue = (ObjectX)processList.getValue(); => You should cast the value you got from the Service back to the Object you want to use.
If is just Object, you may not have to. But I doubt if you will ever have to use just Object.
also see processList.setOnFailed(), processList.setOnRunning(), processList.setOnCancelled(), processList.setOnScheduled(),
You can also bind some GUI elements to some Thread properties like this
label.textProperty.bind( process.messageProperty ); // messageProperty is a StringProperty
progressBar.progressProperty.bind( process.progressProperty )
make sure all the methods to further enhance your process have been created and initiated before calling the process.start(); Nothing happens until you have started the process.
I hope this helps
The Service class provides methods so you know if it has been cancelled,succeded or failed.
In the Constructor of your Class which extends Service use these methods :
// succeeded?
this.setOnSucceeded(s -> {
// ...
});
// failed
this.setOnFailed(f -> {
// ...
});
// cancelled?
this.setOnCancelled(c -> {
// ...
});
Also remember to use updateProgress(current,maximum); so you know what is happening during it's execution.
Here is a full example:
import javafx.concurrent.Service;
import javafx.concurrent.Task;
public class ExampleService extends Service<Boolean> {
/**
* Constructor
*/
public ExampleService() {
// succeeded?
this.setOnSucceeded(s -> {
// ...
});
// failed
this.setOnFailed(f -> {
// ...
});
// cancelled?
this.setOnCancelled(c -> {
// ...
});
}
#Override
protected Task<Boolean> createTask() {
return new Task<Boolean>(){
#Override
protected Boolean call() throws Exception {
boolean result = false;
//your code
//.......
//updateProgress(current,total)
return result;
}
};
}
}
Related
I'm having issues creating a context menu for a WebView.
private void createContextMenuForButton(){
MenuItem clickButton = new MenuItem("Click");
clickButton.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent evt){
addStep();
ListItem item = ListItem.getListView().getItems().get(ListItem.getListView().getItems().size()-1);
item.setComboBoxValue("Click");
*String value = ((Element)evt.getTarget()).getAttribute("value").toString();*
item.getWindow();
}
});
listViewItemContextMenu.getItems().remove(0, listViewItemContextMenu.getItems().size());
listViewItemContextMenu.getItems().add(clickButton);
}
When I run the method above I get the follow exception. Line 190 is marked with *. No matter how I try to get the elements of an ActionEvent it continue to get the error. I can't create an #FXML MenuItem because I need to be able to create new and different menuItem on the fly.
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: javafx.scene.control.MenuItem cannot be cast to org.w3c.dom.Element
at model.WebBrowser$4.handle(WebBrowser.java:190)
at model.WebBrowser$4.handle(WebBrowser.java:1)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
From the exception, it looks like you are trying to cast a JavaFX MenuItem object to an Element type from the Java API for DOM from W3C. That doesn't make any sense. Doesn't it work without the cast, if what you are after is the value of the MenuItem? Try casting it to MenuItem instead of Element.
edit:
Ok had a more close look at it. Looks like it should be something like this, if what you want is the text value of the property text:
String value = ((MenuItem)evt.getTarget()).getText();
I have a code which sets the active selection of the ESelectionService when the user selects something in the tree. Like here:
treeViewer.addSelectionChangedListener(new SelectionChangedListener() {
#Override
public void selectionChanged(SelectionChangedEvent event) {
if (selectionService != null) {
selectionService.setSelection(((IStructuredSelection) event.getSelection()).getFirstElement());
}
}
});
where selectionService is being injected. So far so good.
I also have some command handlers with their own canExecute() methods. In these methods I check the current selection (which is also being injected) and decide if the canExecute() method should return true or false. What I also do in this method is, I also change the visibility of the corresponding HandledToolItem - like here https://stackoverflow.com/a/23602909/2097228.
Now what I experience is that sometimes the call to the setSelection method of the ESelectionService throws a ConcurrentModificationException. This actually occurs when the ToolItemUpdater accesses the itemsToCheck ArrayList.
Is my approach error-prone or is this just a bug in 4.4?
Here is the stacktrace:
Exception occurred
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at org.eclipse.e4.ui.workbench.renderers.swt.ToolItemUpdater.updateContributionItems(ToolItemUpdater.java:36)
at org.eclipse.e4.ui.workbench.renderers.swt.ToolBarManagerRenderer$8.changed(ToolBarManagerRenderer.java:367)
at org.eclipse.e4.core.internal.contexts.TrackableComputationExt.update(TrackableComputationExt.java:110)
at org.eclipse.e4.core.internal.contexts.EclipseContext.processScheduled(EclipseContext.java:338)
at org.eclipse.e4.core.internal.contexts.EclipseContext.set(EclipseContext.java:352)
at org.eclipse.e4.ui.internal.workbench.swt.E4Application$4.changed(E4Application.java:842)
at org.eclipse.e4.core.internal.contexts.TrackableComputationExt.update(TrackableComputationExt.java:110)
at org.eclipse.e4.core.internal.contexts.EclipseContext.processScheduled(EclipseContext.java:338)
at org.eclipse.e4.core.internal.contexts.EclipseContext.set(EclipseContext.java:352)
at org.eclipse.e4.ui.internal.workbench.SelectionAggregator$7.changed(SelectionAggregator.java:228)
at org.eclipse.e4.core.internal.contexts.TrackableComputationExt.update(TrackableComputationExt.java:110)
at org.eclipse.e4.core.internal.contexts.EclipseContext.processScheduled(EclipseContext.java:338)
at org.eclipse.e4.core.internal.contexts.EclipseContext.set(EclipseContext.java:352)
at org.eclipse.e4.ui.internal.workbench.SelectionServiceImpl.setSelection(SelectionServiceImpl.java:31)
at com.e4test.parts.SamplePart$TreeViewerSelectionListener.selectionChanged(SamplePart.java:116)
I created two services public String add(int x, int y) and public String sub(int x, int y). Now, the definition of these services are as follows:
package com.webservice.calc;
import javax.jws.WebService;;
#WebService
public class Calculator {
String s;
public String add(int x, int y)
{
s = "Sum of "+x+" and "+y+" is : "+(x+y);
return s;
}
public String sub(int x, int y)
{
s = "Sum of "+x+" and "+y+" is : "+(x-y);
return s;
}
}
Instead of writing Difference, I wrote Sum in the sub service as well.
Then I used, wsgen tool to generate the wsdl file and using Endpoint publisher, I published it.
Then, I created another project (Web Service Consumer) and using wsimport, imported the web service.
The code went fine. But, now I wanted to change the Sum to Difference.
I changed the code in the original code, then used wsgen, then republished (here there was an error:
Exception in thread "main" Server Runtime Error: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.HttpEndpoint.publish(Unknown Source)
at com.sun.xml.internal.ws.transport.http.server.EndpointImpl.publish(Unknown Source)
at com.sun.xml.internal.ws.spi.ProviderImpl.createAndPublishEndpoint(Unknown Source)
at javax.xml.ws.Endpoint.publish(Unknown Source)
at com.webservice.calc.endpoint.CalcEndpointPublisher.main(CalcEndpointPublisher.java:12)
Caused by: Server Runtime Error: java.net.BindException: Address already in use: bind
at com.sun.xml.internal.ws.transport.http.server.ServerMgr.createContext(Unknown Source)
... 5 more
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind(Native Method)
at sun.nio.ch.ServerSocketChannelImpl.bind(Unknown Source)
at sun.nio.ch.ServerSocketAdaptor.bind(Unknown Source)
at sun.net.httpserver.ServerImpl.<init>(Unknown Source)
at sun.net.httpserver.HttpServerImpl.<init>(Unknown Source)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(Unknown Source)
at com.sun.net.httpserver.HttpServer.create(Unknown Source)
... 6 more
) it and again imported it. But no changes. What is the issue here?
Question 1: I have created a sample java application using play 2.1.1 with a scheduler to be kicked off when the application is started. I did a play compile and then play start, but i'm getting the below error, please let me know if i'm doing anything wrong here:
(Starting server. Type Ctrl+D to exit logs, the server will remain in background)
Play server process ID is 6160
#6edl861on: Cannot init the Global objectOops, cannot start the server.
at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:57)
at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:51)
at play.utils.Threads$.withContextClassLoader(Threads.scala:18)
at play.api.WithDefaultGlobal$class.play$api$WithDefaultGlobal$$globalInstance(Application.scala:50)
at play.api.DefaultApplication.play$api$WithDefaultGlobal$$globalInstance$lzycompute(Application.scala:383)
at play.api.DefaultApplication.play$api$WithDefaultGlobal$$globalInstance(Application.scala:383)
at play.api.WithDefaultGlobal$class.global(Application.scala:66)
at play.api.DefaultApplication.global(Application.scala:383)
at play.api.WithDefaultConfiguration$class.play$api$WithDefaultConfiguration$$fullConfiguration(Application.scala:80)
at play.api.DefaultApplication.play$api$WithDefaultConfiguration$$fullConfiguration$lzycompute(Application.scala:383)
at play.api.DefaultApplication.play$api$WithDefaultConfiguration$$fullConfiguration(Application.scala:383)
at play.api.WithDefaultConfiguration$class.configuration(Application.scala:82)
at play.api.DefaultApplication.configuration(Application.scala:383)
at play.api.Application$class.$init$(Application.scala:268)
at play.api.DefaultApplication.<init>(Application.scala:383)
at play.core.StaticApplication.<init>(ApplicationProvider.scala:52)
at play.core.server.NettyServer$.createServer(NettyServer.scala:228)
at play.core.server.NettyServer$$anonfun$main$5.apply(NettyServer.scala:259)
at play.core.server.NettyServer$$anonfun$main$5.apply(NettyServer.scala:258)
at scala.Option.map(Option.scala:145)
at play.core.server.NettyServer$.main(NettyServer.scala:258)
at play.core.server.NettyServer.main(NettyServer.scala)
Caused by: java.lang.RuntimeException: There is no started application
at scala.sys.package$.error(package.scala:27)
at play.api.Play$$anonfun$current$1.apply(Play.scala:46)
at play.api.Play$$anonfun$current$1.apply(Play.scala:46)
at scala.Option.getOrElse(Option.scala:120)
at play.api.Play$.current(Play.scala:46)
at play.api.Play.current(Play.scala)
at play.libs.Akka.system(Akka.java:25)
at Global.<init>(Global.java:27)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at play.api.WithDefaultGlobal$class.play$api$WithDefaultGlobal$$javaGlobal(Application.scala:30)
at play.api.DefaultApplication.play$api$WithDefaultGlobal$$javaGlobal$lzycompute(Application.scala:383)
at play.api.DefaultApplication.play$api$WithDefaultGlobal$$javaGlobal(Application.scala:383)
at play.api.WithDefaultGlobal$$anonfun$play$api$WithDefaultGlobal$$globalInstance$1.apply(Application.scala:52)
Resources:
Global.java - in apps/
public class Global extends GlobalSettings {
private Logger.ALogger log = Logger.of(Global.class);
private ActorRef myActor = Akka.system().actorOf(
new Props(Retreiver.class));
#Override
public void onStart(Application app) {
log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Akka.system()
.scheduler()
.schedule(Duration.create(0, TimeUnit.MILLISECONDS),
Duration.create(10, TimeUnit.SECONDS), myActor, "tick",
Akka.system().dispatcher());
}
}
Retreiver.java:
public class Retreiver extends UntypedActor {
private Logger.ALogger log = Logger.of(TweetsRetreiver.class);
#Override
public void onReceive(Object arg0) throws Exception {
// some code here
}
}
application.conf:
application.global=Global
Question 2: Also, No logs are getting printed either in the console or Application.log file. I have used play.Logger package to do the logging, is this the correct package to be used to log in play 2.1.1? Please provide an example for this.
Thanks.
Solved. Problem with the line:
private ActorRef myActor = Akka.system().actorOf(
new Props(Retreiver.class));
When i moved this inside the onStart method, it got triggered correctly. Don't know why i can't define this in class level. Need to check.
For the logging question, you have to use the Play's Logger helper :
#Override
public void onStart(Application app) {
play.Logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
...
}
Whatever I do I cannot create new instance of class Serwer. Please help, somehow constructor is invisible. I don't understand why is it so. The constructor is public and everything is coded in one file.
I just get this:
java.rmi.StubNotFoundException: Stub class not found: Serwer_Stub; nested exception is:
java.lang.ClassNotFoundException: Serwer_Stub
at sun.rmi.server.Util.createStub(Unknown Source)
at sun.rmi.server.Util.createProxy(Unknown Source)
at sun.rmi.server.UnicastServerRef.exportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.exportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.exportObject(Unknown Source)
at com.sun.corba.se.impl.javax.rmi.PortableRemoteObject.exportObject(Unknown Source)
at javax.rmi.PortableRemoteObject.exportObject(Unknown Source)
at javax.rmi.PortableRemoteObject.<init>(Unknown Source)
at Serwer.<init>(Serwer.java:13)
at Serwer.main(Serwer.java:35)
Caused by: java.lang.ClassNotFoundException: Serwer_Stub
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
... 10 more
CLASS
import java.rmi.RemoteException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.rmi.PortableRemoteObject;
public class Serwer extends PortableRemoteObject implements MyInterface {
public Serwer() throws RemoteException {
super();
try{
Serwer ref =
new Serwer();
Context ctx = new InitialContext();
ctx.rebind("myinterfaceimplementacja", ref);
}catch(Exception e){e.printStackTrace();}
}
#Override
public String echo(String napis) throws RemoteException {
return "echo" + napis;
}
#Override
public int dodaj(int wrt1, int wrt2) throws RemoteException {
return wrt1 + wrt2;
}
public static void main(String[] args){
try {
new Serwer();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There are two bugs in your code. The first one is the obvious infinite recursion in the Serwer constructor, where you are calling the constructor again and again. This can be fixed by removing that line from the constructor and replace ref with this on the following line:
public class Serwer extends PortableRemoteObject implements MyInterface {
public Serwer() throws RemoteException {
super();
}
#Override
public String echo(String napis) throws RemoteException {
return "echo" + napis;
}
#Override
public int dodaj(int wrt1, int wrt2) throws RemoteException {
return wrt1 + wrt2;
}
public static void main(String[] args){
try {
Serwer ref = new Serwer();
// Context ctx = new InitialContext();
// ctx.rebind("myinterfaceimplementacja", ref);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
However, this bug is unrelated to the ClassNotFoundException you got. What causes the exception is that you use PortableRemoteObject as the base class of your remote implementation. Normally in Java RMI, the stub class (Serwer_Stub) is generated automatically when you export (instantiate) the remote object. But the PortableRemoteObject is an exception to this case. You can solve this two ways:
As Kumar suggested, replace the javax.rmi.PortableRemoteObject with java.rmi.server.UnicastRemoteObject. This way the stub object gets created automatically, and the above code will run happily, I tested it.
public class Serwer extends UnicastRemoteObject implements MyInterface {
If for some reason you must use PortableRemoteObject, then you should generate the stub class manually by using the RMI compiler (rmic) tool that are shipped with the JDK.
First, you compile the Serwer class:
javac Serwer.java
This will generate the Serwer.class file. Then you call the RMIC tool to generate the stub class:
rmic Serwer
This will generate the Serwer_Stub.class file. Now you can run your server:
java Serwer
I also tested this, it starts without any exceptions.
Note that there is another bug in your code with the usage of the Java Naming, causing another exception (NoInitialContextException), but that is also unrelated with the question, that's why I commented it out in the code above. Since I'm no expert in javax.naming, it's up to someone else to help you with that.
Maybe you intended to use RMI registry instead of using Naming by mistake. RMI registry is the native way to bind and lookup remote objects in Java RMI. In this case you should replace the
Context ctx = new InitialContext();
ctx.rebind("myinterfaceimplementacja", ref);
lines with the appropriate RMI registry code:
Registry reg = LocateRegistry.createRegistry(1099);
reg.rebind("myinterfaceimplementacja", ref);
This will create the RMI registry for you on the standard port (1099). If you run your program, the registry will be created and your remote object will be exported and registered under the given name.
The other way is to write
Registry reg = LocateRegistry.getRegistry();
This makes your program to find an existing registry that is already running. You must start the RMI registry before running your program, by calling the remiregistry tool, that is also part of the JDK:
rmiregistry
Now you can compile and you start your program:
javac Serwer.java
java Serwer
It will start and register your remote object implementation in the registry, making it available to be looked up by the clients.