play framework scheduler with Akka at server launch - java

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(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
...
}

Related

Max cycling74 mxj dependency

My goal: Running Processing.org (version 3.5.4) from Max (cycling74) version 8 on Windows 10 64 through writing an MXJ external (Max Java support). I want to open a processing test sketch within window from MAX by sending a bang message to the MXJ external. For this I have
class MaxJavaTest3 extends MaxObject which calls
class TestProcessing extends PApplet.
public class MaxJavaTest3 extends MaxObject {
public void bang() {
String[] args = {};
TestProcessing.main(args);
}
}
public class TestProcessing extends PApplet {
public static void main(String args[] ) {
PApplet.main("TestProcessing", args);
}
public void settings() {
size(920, 780);
}
public void setup() {
background(0);
fill(255, 0, 0);
circle(width/2, height/2, 80);
}
}
In IntelliJ, I set the dependencies for Max and Java. The bang message is received in Java e.g. triggering some text messages to the console. If I execute PApplet.main via the entry point TestProcessing.main, the processing window opens. So far so good, but trying to invoke PApplet.main via MaxJavaTest3.bang() method I get the error:
java.lang.RuntimeException: java.lang.ClassNotFoundException: TestProcessing
at processing.core.PApplet.runSketch(PApplet.java:10852)
at processing.core.PApplet.main(PApplet.java:10657)
at TestProcessing.main(TestProcessing.java:11)
at MaxJavaTest3.bang(MaxJavaTest3.java:19)
Caused by: java.lang.ClassNotFoundException: TestProcessing
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at processing.core.PApplet.runSketch(PApplet.java:10845)
... 3 more
```JAVA
I found a post which suggests that there is a problem with Max using ProcessingĀ“s OpenGL related capacities: "since OpenGL uses also native libraries (*.dll files) and not only *.jar files. I don't know if its possible in MaxMSP - that depends on how they set up their JVM."
https://forum.processing.org/one/topic/use-processing-from-within-max-msp-or-from-matlab.html

When using Advice of byte buddy, Exception of java.lang.NoClassDefFoundError is throwed

For some reason, I've been analyzing my own old jar file(unfortunately source code's been lost).
I know what part I'm going to find but can't remember where it is.
So decide to use byte buddy to get all the run flow of jar file. It's enough to log parameter values and return values of all methods in all classes(except library class, e.g, java.lang.*).
I tried sample codes with a little modification, but straggle with just an exception:
public static void premain(final String agentArgs,
final Instrumentation inst) {
System.out.println(
"+++Hey, look: I'm instrumenting a freshly started JVM!");
new AgentBuilder.Default()
.type(ElementMatchers.any())
.transform(new MetricsTransformer())
.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
.with(AgentBuilder.TypeStrategy.Default.REDEFINE)
.installOn(inst);
}
private static class MetricsTransformer implements AgentBuilder.Transformer {
#Override
public DynamicType.Builder<?> transform(
final DynamicType.Builder<?> builder,
final TypeDescription typeDescription,
final ClassLoader classLoader,
final JavaModule module) {
final AsmVisitorWrapper methodsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceMethods.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isMethod()));
final AsmVisitorWrapper constructorsVisitor =
Advice.to(EnterAdvice.class, ExitAdviceConstructors.class)
.on(ElementMatchers.isAnnotatedWith(CollectMetrics.class)
.and(ElementMatchers.isConstructor()));
return builder.visit(methodsVisitor).visit(constructorsVisitor);
}
private static class EnterAdvice {
#Advice.OnMethodEnter
static long enter() {
return System.nanoTime();
}
}
private static class ExitAdviceMethods {
#Advice.OnMethodExit(onThrowable = Throwable.class)
static void exit(#Advice.Origin final Executable executable,
#Advice.Enter final long startTime,
#Advice.Thrown final Throwable throwable) {
final long duration = System.nanoTime() - startTime;
System.out.println(duration);;
}
}
}
byte buddy's versions are 1.9.5, 1.7.11
jdk version: 1.8.0.191
and the Exception in the cmd:
E:\>cd E:\workshop\_android_studio\BounAgent\out\artifacts\BounAgent_jar
E:\BounAgent_jar>java -javaagent:BounAgent.jar -jar untitled.jar
Exception in thread "main" java.lang.NoClassDefFoundError: net/bytebuddy/matcher
/ElementMatcher
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Sou
rce)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown So
urce)
Caused by: java.lang.ClassNotFoundException: net.bytebuddy.matcher.ElementMatche
r
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)
... 5 more
FATAL ERROR in native method: processing of -javaagent failed
Thanks in advance.
According to an article I found:
To launch your agent you must bundle the agent classes and resources in a jar, and in the jar manifest set the Agent-Class property to the name of your agent class containing the premain method. (An agent must always be bundled as a jar file, it cannot be specified in an exploded format.)
It appears that your agent JAR file ("BounAgent.jar") does not contain all of the dependencies in the correct form. Specifically, the bytebuddy classes are not in the JAR file. That is causing the agent classes to fail to load.

JavaFX: Service and GUI

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;
}
};
}
}

Scala Script Engine creating another instance of a singleton

So, I'm creating a scripting system using JSR 223 for Scala, but I came across this problem I can't find any cause for.
There is a singleton-like class, which has methods to add event listeners (from the scripts) and dispatch events (from the core). Everything worked fine, but for some reason the added listeners had disappeared when I got to dispatch an event.
After reproducing the problem, I found out that the script engine creates another instance of the singleton:
Here is my Singleton class:
package test;
import java.util.Arrays;
public final class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
Arrays.stream(Thread.currentThread().getStackTrace()).forEach(System.out::println);
System.out.println();
}
public static Singleton instance() {
return instance;
}
}
And here is my Main class:
package test;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public final class Main {
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");
// this is a trick I found to access the classpath,
// might be the problem
#SuppressWarnings("rawtypes")
scala.collection.immutable.List nil = scala.collection.immutable.Nil$.MODULE$;
#SuppressWarnings("unchecked")
scala.collection.immutable.$colon$colon<String> vals = scala.collection.immutable.$colon$colon$.MODULE$.apply("true", nil);
((scala.tools.nsc.interpreter.IMain) engine).settings().usejavacp().tryToSet(vals);
engine.eval("test.Singleton.instance");
Singleton.instance();
}
}
And here is the output:
java.lang.Thread.getStackTrace(Unknown Source)
test.Singleton.<init>(Singleton.java:10)
test.Singleton.<clinit>(Singleton.java:7)
$line3.$read$$iw$$iw$.<init>(<console>:8)
$line3.$read$$iw$$iw$.<clinit>(<console>)
$line3.$eval$.$result$lzycompute(<console>:5)
$line3.$eval$.$result(<console>:5)
$line3.$eval.$result(<console>)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:773)
scala.tools.nsc.interpreter.IMain$ReadEvalPrint.callEither(IMain.scala:777)
scala.tools.nsc.interpreter.IMain$ReadEvalPrint.evalEither(IMain.scala:792)
scala.tools.nsc.interpreter.IMain$WrappedRequest.eval(IMain.scala:613)
scala.tools.nsc.interpreter.IMain.eval(IMain.scala:1047)
javax.script.AbstractScriptEngine.eval(Unknown Source)
test.Main.main(Main.java:19)
java.lang.Thread.getStackTrace(Unknown Source)
test.Singleton.<init>(Singleton.java:10)
test.Singleton.<clinit>(Singleton.java:7)
test.Main.main(Main.java:20)
The stack trace shows that the script engine ends up creating a new instance of Singleton, but I got no idea why.
Thank you.
Found out the fix after browsing the source code:
((scala.tools.nsc.interpreter.IMain) engine).settings().embeddedDefaults(Main.class.getClassLoader());
This changes the ClassLoader for the ScriptEngine to the same one.

Why the Class cannot be seen in its source file Java

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.

Categories