Unable to connect to RMI server when running Client from Servlet [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
Have a Java servlet running using a Tomcat server. So when the servlet starts, I would like the client to connect to a RMI registry (Port 33996). The client is initialized during the init() of the servlet. However, for some reason, it is unable to connect to the server
Server code
#Override
public void startRMIRegistry(CentralServer server){
try {
AsyncLogger.log("Setting up RMI Registry.....");
Registry registry = LocateRegistry.createRegistry(
Integer.parseInt(ServerConfigUtils.getProperty(ServerConfigUtils.PORT)));
registry.rebind(ServerConfigUtils.getProperty(ServerConfigUtils.NAME), server);
} catch (RemoteException e) {
e.printStackTrace();
}
}
Client code
private ICentralServer getServerConnection() {
String serverHost = ServerConfigUtils.getProperty(ServerConfigUtils.HOST);
Integer serverPort = Integer.valueOf(ServerConfigUtils.getProperty(ServerConfigUtils.PORT));
String serverName = ServerConfigUtils.getProperty(ServerConfigUtils.NAME);
Integer failureCount = 0;
while (failureCount < SERVER_ACTION_ATTEMPTS) {
try {
return (ICentralServer)
LocateRegistry.getRegistry(serverHost, serverPort).lookup(serverName);
} catch (Exception e) {
failureCount++;
continue;
}
}
AsyncLogger.log("Failed to connect to central server, giving up");
throw new RuntimeException();
}
Servlet
#Override
public void init() throws ServletException {
try {
client = new LabClient();
} catch (Exception e) {
e.printStackTrace();
}
super.init();
}
Error
INFO: Starting ProtocolHandler ["http-nio-8080"]
sg.gov.moh.exceptions.CannotReachServerException: java.lang.NullPointerException
at sg.gov.moh.client.LabClient.<init>(LabClient.java:366)
at launcher.servlet.MainServlet.init(MainServlet.java:36)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1152)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1097)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:768)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:364)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:624)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1651)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
at sg.gov.moh.centralServer.CentralServer.pingOrPrune(CentralServer.java:318)
at sg.gov.moh.centralServer.CentralServer.registerLaboratory(CentralServer.java:297)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:357)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:573)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:834)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:688)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:687)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:303)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:279)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:163)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:235)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:180)
at com.sun.proxy.$Proxy5.registerLaboratory(Unknown Source)
at sg.gov.moh.client.LabClient.registerCallback(LabClient.java:69)
at sg.gov.moh.client.LabClient.<init>(LabClient.java:364)
... 21 more
Had my peers tried this code, they were all able to connect successfully.
Have tried toggling off firewall, setting inbound rules to the port but to no avail

Found the solution, I ran mvn clean package at the parent maven directory, previously I was rebuilding the sub-modules invidually at sub-module level, which corrupted the bytecode.
|- Parent
| |--Sub-module a
| |--Sub-module b
|
|

Related

com.google.firebase.messaging.FirebaseMessagingException: Error while calling FCM backend service

I am trying to send the fcm notification :
MulticastMessage message = MulticastMessage.builder()
.addAllTokens(registrationTokens)
.putAllData(body)
.build();
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
BatchResponse response = FirebaseMessaging.getInstance().sendMulticast(message);
Sometimes the code on the server encounters this problem
com.google.firebase.messaging.FirebaseMessagingException: Error while calling FCM backend service
at com.google.firebase.messaging.FirebaseMessagingClientImpl.sendAll(FirebaseMessagingClientImpl.java:142)
at com.google.firebase.messaging.FirebaseMessaging$2.execute(FirebaseMessaging.java:293)
at com.google.firebase.messaging.FirebaseMessaging$2.execute(FirebaseMessaging.java:290)
at com.google.firebase.internal.CallableOperation.call(CallableOperation.java:36)
at com.google.firebase.messaging.FirebaseMessaging.sendAll(FirebaseMessaging.java:183)
at com.google.firebase.messaging.FirebaseMessaging.sendMulticast(FirebaseMessaging.java:252)
at com.google.firebase.messaging.FirebaseMessaging.sendMulticast(FirebaseMessaging.java:227)
at ir.mirorim.vn.serviceImp.userService.NotificationServiceImp.sendMultipleMessage(NotificationServiceImp.java:351)
at ir.mirorim.vn.serviceImp.userService.NotificationServiceImp.testNotification(NotificationServiceImp.java:130)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1623)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
What i am doing wrong. All the config are with the code while compilation.
The part where I load the Firebase configuration file
#PostConstruct
public void init() {
try {
String configPath = servletContext.getRealPath("/WEB-INF/mm-firebase-adminsdk-oqtey-c111bb111c.json");
FileInputStream serviceAccount =
new FileInputStream(configPath);
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.setDatabaseUrl("https://****-****.firebaseio.com")
.build();
FirebaseApp.initializeApp(options);
}
catch (Exception e){
e.printStackTrace();
}
}
my json config:
{
"type": "service_account",
"project_id": "mm-1111",
"private_key_id": "**************************",
"private_key": "-----BEGIN PRIVATE KEY-----
xxx
---END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-kvj7w#mm-1111.iam.gserviceaccount.com",
"client_id": "1000559483501236*****",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-kvj7w%mm-1111.iam.gserviceaccount.com"
}
Are these server blocked or what? How should I debug those?
Can anyone help me?

Java - Unable to add my MySQL JAR file into build path of eclipse

public void service(HttpServletRequest req,HttpServletResponse res){
PrintWriter out;
try {
out = res.getWriter();
} catch (IOException e2) {
e2.printStackTrace();
System.out.println("IO thrown");
}
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
System.out.println("Instantiation exception thrown");
} catch (IllegalAccessException e1) {
e1.printStackTrace();
System.out.println("illegal access exception thrown");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
System.out.println("class not found thrown");
}
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQL exception thrown");
}
System.out.println("connection failure");
}
I tried to add JAR file into Properties->Build path and into that I added my JAR into either of both Modulopath as well as Classpath separately but neither of it works because each time I had a same exception as
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1358)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:332)
at com.practice.Form1.service(Form1.java:23)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
connection failure
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:609)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1623)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:835)
I'm confused exactly where to add MySQL JAR because I'm unable to add it into Property->Build Path->Library directly as shown in the image
When I open Property->Build path it doesn't let me add MySQL JAR (as External JAR) directly, I have to select either Modulopath or Classpath
if Eclipse really doesn't give you a good response, you can directly modify the hidden file (.classpath)
<classpathentry kind="lib" path="WEB-INF/lib/mysql-connector-java-3.0.14-production-bin.jar"/>
I assume that your jar file is in place.
rename the mysql connector version that you using
hope it helps.

Remote forward() invocation of ProcessorContext throws NPE

I use Apache Kafka Streams the Processor API.
I create a remote object that extends the UnicastRemoteObject inside the StateStore of the Processor.
When the init(ProcessorContext) method of the Processor (which extends the AbstractProcessor) of my topology is called I put a ProcessorContext reference inside that remote Object.
public void init(ProcessorContext processorContext){
super.init(processorContext);
this.myStore = (MyCustomStore<String, String>)context().getStateStore("mystore");
this.myStore.getRemoteObject().setProcessorContext(processorContext);
}
If I access the ProcessorContext only remotely and use the forward method to send records to a sink processor it works fine. And if I access the ProcessorContext only locally to send records with forward it works fine, too.
If I access the ProcessorContext both locally and remotely to use forward I have NPE. I used a synchronized method in which foward is called because I thought that two different threads try to access ProcessorContext at the same time but the NPE insists.
It seems to me that somehow the same thread calls forward at the same time
both locally and remotely and that throws NPE.
The message is:
java.lang.NullPointerException
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:114)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:90)
at StateMessageBean.sendMessage(StateMessageBean.java:109)
at StateMessageBean.subroundEnded(StateMessageBean.java:87)
at sun.reflect.GeneratedMethodAccessor26.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:361)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:283)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:260)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:161)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:227)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:179)
at com.sun.proxy.$Proxy25.subroundEnded(Unknown Source)
at CoordinatorProcessor.collectIncreaseOfC(CoordinatorProcessor.java:332)
at CoordinatorProcessor.process(CoordinatorProcessor.java:119)
at CoordinatorProcessor.process(CoordinatorProcessor.java:25)
at org.apache.kafka.streams.processor.internals.ProcessorNode$1.run(ProcessorNode.java:50)
at org.apache.kafka.streams.processor.internals.ProcessorNode.runAndMeasureLatency(ProcessorNode.java:244)
at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:133)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:143)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:126)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:90)
at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:87)
at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:302)
at org.apache.kafka.streams.processor.internals.AssignedStreamsTasks.process(AssignedStreamsTasks.java:94)
at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:409)
at org.apache.kafka.streams.processor.internals.StreamThread.processAndMaybeCommit(StreamThread.java:964)
at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:832)
at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:767)
at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:736)
The two methods that I call remotely and locally are:
//remote method
#Override
public void subroundEnded()
{
PhiMessage newPhiMessage = new PhiMessage();
newPhiMessage.setSiteId(this.siteId);
newPhiMessage.setCurrentRound(this.currentRound);
newPhiMessage.setCurrentSubround(this.currentSubround);
newPhiMessage.setPhi(this.phi);
byte[] byteNewPhiMessage = SerializationUtils.serialize(newPhiMessage);
this.processorContext.forward("PhiMessage", byteNewPhiMessage);
}
//local method
public void sendIncrease()
{
IncreaseMessage increaseMessage = new IncreaseMessage();
increaseMessage.setCurrentRound(this.currentRound);
increaseMessage.setCurrentSubround(this.currentSubround);
increaseMessage.setIncrease(this.increase);
byte[] byteIncreaseMessage = SerializationUtils.serialize(increaseMessage);
this.processorContext.forward("IncreaseMessage", byteIncreaseMessage);
}

Error 500 in JsonObjectRequest in Android

I'm struggling with error 500 during sending a JSON Object to my Server. I'm using POST method because I need to save user in the database. I suppose something is wrong in my request cause the output doesn't print (in onResponse method). On the server side, the data is not printed too but there is no exception handled, no errors - everything going okay but data is still not there!
Android register method:
public class RegisterIndividualActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_individual);
setListeners();
}
private void setListeners() {
final EditText loginField = (EditText) findViewById(R.id.loginField);
final EditText passwordField = (EditText) findViewById(R.id.passwordField);
Button registerButton = (Button) findViewById(R.id.registerButton);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register(
loginField.getText(),
passwordField.getText(),
);
}
});
}
private void register(final Editable login,
final Editable password){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Creating new acc...");
progressDialog.show();
RequestQueue queueAcc = Volley.newRequestQueue(this);
String urlAcc = getResources().getString(R.string.server_address)+"android/user/register?login="
+ login.toString() + "&password=" + password.toString();
JSONObject newUser = new JSONObject();
try {
newUser.put("login", login.toString());
newUser.put("password", password.toString());
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("USER TO SAVE: " + newUser.toString());
JsonObjectRequest urlAccStringRequest = new JsonObjectRequest(Request.Method.POST, urlAcc, newUser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println("Good morning " + login.toString()); //doesnt print
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { //i got this error
progressDialog.dismiss();
Toast.makeText(RegisterIndividualActivity.this, "Connection error", Toast.LENGTH_SHORT).show();
}
});
queueAcc.add(urlAccStringRequest);
queueAcc.start();
}
}
The controller on the server side (this is in proper class with #Controller adnotation and needed mapping which is android/user):
#RequestMapping(value = "/register", method = RequestMethod.POST)
public void register(
#RequestParam("login") String login,
#RequestParam("password") String password,
HttpServletRequest request, HttpServletResponse response, Model model
){
System.out.println("\nIn Register method..");
UserModel uM = new UserModel();
HttpSession session = request.getSession(true);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
uM.setAccountType("Client");
JsonParser parser = new JsonParser();
try {
System.out.println("\nTrying to save..");
JsonObject jsonObject = (JsonObject) parser.parse(request.getReader());
System.out.println(jsonObject.get("login").toString()); //event this doesnt print
uM.setLogin(jsonObject.get("login").toString());
uM.setPassword(jsonObject.get("password").toString());
System.out.println(uM.toString()); //doesnt print
userDAO.save(uM);
} catch (IOException e) { // doesnt throw exception
e.printStackTrace();
}
System.out.println(uM.toString()); // doesnt print
}
#EDIT Added server log:
19-Jun-2017 19:42:22.757 SEVERE [http-nio-8080-exec-1] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [spring-mvc] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: com.google.gson.JsonObject cannot be cast to javax.json.JsonObject] with root cause
java.lang.ClassCastException: com.google.gson.JsonObject cannot be cast to javax.json.JsonObject
at com.mvc.controller.AndroidUserController.register(AndroidUserController.java:145)
at com.mvc.controller.AndroidUserController$$FastClassBySpringCGLIB$$448b2d05.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.mvc.controller.AndroidUserController$$EnhancerBySpringCGLIB$$47d3305.register(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
#EDIT 2
This is server log after changing try-catch block to this:
try {
System.out.println("\nTrying to save..");
JsonObject jsonObject = (JsonObject) parser.parse(request.getReader());
System.out.println(jsonObject.get("login").toString()); //event this doesnt print
} catch (IOException e) { // doesnt throw exception
e.printStackTrace();
}
Server log:
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
#EDIT 3!!!!
I figured out that this line is cousing the errors showed in the second server log:
JsonObject jsonObject = (JsonObject) parser.parse(request.getReader());
What's wrong with that?
#EDIT 4
This is my current code for reading the json:
try {
System.out.println("\nTrying to save...");
InputStream inputStream = request.getInputStream();
JsonReader reader = Json.createReader(inputStream); //this is were error is
reader.close();
// JsonObject jsonObject = reader.readObject();
// reader.close();
// System.out.println(jsonObject.get("login").toString());
//// uM.setLogin(jsonObject.get("login").toString());
// uM.setPassword(jsonObject.get("password").toString());
// System.out.println(uM.toString());
// userDAO.save(uM);
} catch (IOException e) {
e.printStackTrace();
}
And this is current server log:
19-Jun-2017 21:36:34.490 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
19-Jun-2017 21:36:34.617 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
19-Jun-2017 21:36:46.631 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'spring-mvc'
19-Jun-2017 21:36:57.007 SEVERE [http-nio-8080-exec-4] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [spring-mvc] in context with path [] threw exception [Request processing failed; nested exception is javax.json.JsonException: Provider org.glassfish.json.JsonProviderImpl not found] with root cause
java.lang.ClassNotFoundException: org.glassfish.json.JsonProviderImpl
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at javax.json.spi.JsonProvider.provider(JsonProvider.java:94)
at javax.json.Json.createReader(Json.java:220)
at com.mvc.controller.AndroidUserController.register(AndroidUserController.java:146)
at com.mvc.controller.AndroidUserController$$FastClassBySpringCGLIB$$448b2d05.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.mvc.controller.AndroidUserController$$EnhancerBySpringCGLIB$$f920f9fc_2.register(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:870)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
com.google.gson.JsonObject cannot be cast to javax.json.JsonObject
You seem to have imported the wrong JsonObject class
If you are using Gson, this is not how to parse JSON with it
JsonObject jsonObject = (JsonObject) parser.parse(request.getReader());

Java RMI simple Hello World program throwing RemoteException

I have this strange problem.
I'm trying to write a simple Hello World java program using RMI.
Here are my files, all belonging to the same package:
Hello.java:
package com.something;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote{
String hello() throws RemoteException;
}
Server.java
package com.something;
import com.something.Hello;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello{
#Override
public String hello() throws RemoteException {
return "hello world!!!!";
}
public static void main (String args[]) throws RemoteException{
//System.setProperty("java.rmi.server.hostname", "10.0.0.5");
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
String name = "Hello";
Hello s = new Server();
Hello stub =
(Hello) UnicastRemoteObject.exportObject(s, 0);
Registry registry = LocateRegistry.getRegistry(8888);
registry.rebind(name, stub);
System.out.println("Hello bound");
} catch (Exception e) {
System.err.println("Hello exception:");
e.printStackTrace();
}
}
}
Client.java:
package com.something;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new SecurityManager());
}
try {
String name = "Hello";
Registry registry = LocateRegistry.getRegistry("localhost");
Hello h = (Hello) registry.lookup(name);
System.out.println(h.hello());
} catch (Exception e) {
System.err.println("My exception:");
e.printStackTrace();
}
}
}
Before runnig the code, in the terminal, I run:
rmiregistry 8888
I run the java code with the following flag:
-Djava.security.policy=/Users/nataliazon/Documents/workspace/SiecioweRMI/src/server.policy
And here's my server.policy file:
grant {
permission java.security.AllPermission;
};
When I run the Server program like that, the following exception is thrown:
Hello exception:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: com.something.Hello
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:400)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:248)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:359)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at com.something.Server.main(Server.java:30)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: com.something.Hello
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:390)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:248)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.ClassNotFoundException: com.something.Hello
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at sun.rmi.server.LoaderHandler.loadProxyInterfaces(LoaderHandler.java:709)
at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:653)
at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:590)
at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:628)
at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294)
at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:238)
at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1530)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1492)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1731)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
... 12 more
And the Client program throws this:
My exception:
java.rmi.ConnectException: Connection refused to host: localhost; nested exception is:
java.net.ConnectException: Connection refused
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:601)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:322)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at com.something.Client.main(Client.java:18)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:22)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:128)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:595)
... 5 more
How can this problem be solved?
java.lang.ClassNotFoundException: com.something.Hello
The Registry and the client don't have that class on their classpath.
In the case of the Registry the simplest solution is to start it in the server JVM. via LocateRegistry.createRegistry(): or else start it in such a way that the class is on its classpath; there are several ways to accomplish that.
java.rmi.ConnectException: Connection refused to host: localhost
That is caused by specifying "localhost" instead of the server host when calling Naming.lookup() or when calling LocateRegistry.getRegistry() prior to calling Registry.lookup(). The Registry isn't ubiquitous, it is located at the server host.
NB you don't need the SecurityManager unless you are using the RMI codebase feature or you have some other requirement for it.

Categories