Unknown host RMI java - java

I get an unknown host error when I try to start an RMI server
here. The error is unknown host. Actually, I'm just a beginner in RMI and sockets programming in JAVA. Can you please provide me with some tutorials
concerning my problem.
My interface code:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.sql.ResultSet;
public interface Méthodes {
public String authentification(String login, String mdp) throws RemoteException;
public ResultSet selection(String requete) throws RemoteException;
public int miseAjour(String requete) throws RemoteException;
public String envoyerFichier(File fichier) throws RemoteException;
}
In this class I have all the methods that I need in my program:
package ApplicationServer;
import java.io.File;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Traitements extends UnicastRemoteObject implements Méthodes {
private Connection cnx;
private Statement stm;
private ResultSet rst;
private int rs;
public void setCnx(Connection cnx) {
this.cnx = cnx;
}
public void setStm(Statement stm) {
this.stm = stm;
}
public void setRst(ResultSet rst) {
this.rst = rst;
}
public void setRs(int rs) {
this.rs = rs;
}
protected Traitements() throws RemoteException {
super();
// TODO Auto-generated constructor stub
}
#Override
public String authentification(String login, String mdp) throws RemoteException {
// TODO Auto-generated method stub
try {
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery("select md5('"+mdp+"');");
while(rst.next()){
mdp=rst.getString(1);
}
stm.clearBatch();
stm=cnx.createStatement();
setRst(null);
String Query = "select * from utilisateurs where login like '"+login+"' and motdepasse like '"+mdp+"';";
rst=stm.executeQuery(Query);
int id = 0;
String nm = null;
String prm = null;
while(rst.next()){
id = rst.getInt("id");
nm = rst.getString("nom");
prm = rst.getString("prenom");
}
if(id>0 && nm!=null && prm!=null){
return id+" "+nm+" "+prm;
}
}catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public ResultSet selection(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRst(null);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rst=stm.executeQuery(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
}
#Override
public int miseAjour(String requete) throws RemoteException {
try{
setCnx(null);
setStm(null);
setRs(0);
Class.forName("com.mysql.jdbc.Driver");
cnx=DriverManager.getConnection("jdbc:mysql://localhost:3306/banque","root","");
stm=cnx.createStatement();
rs=stm.executeUpdate(requete);
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rs;
}
#Override
public String envoyerFichier(File fichier) throws RemoteException {
// TODO Auto-generated method stub
return null;
}
}
This is the main class that runs the server:
package ApplicationServer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
int port=12345;
String url="rmi://serveur:"+port+"/reference";
LocateRegistry.createRegistry(port);
Traitements srv = new Traitements();
Naming.rebind(url, srv);
JOptionPane.showMessageDialog(null, "Serveur Lance :");
} catch (RemoteException | MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

You are supposed to replace serveur with a real hostname in that code.
However it's far better to use localhost in the RMI URL when binding. The Registry has to be local to the host anyway so there's no point in using anything else.

Related

How to handle BLOB and CLOB in olingo v2?

Here there is pseudocode about how to handle BLOB and CLOB in olingo jpa. I added the needed imports to the pseudocode:
package me;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.SQLException;
import javax.sql.rowset.serial.SerialException;
import org.apache.olingo.odata2.jpa.processor.api.OnJPAWriteContent;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
public class OnDBWriteContent implements OnJPAWriteContent {
#Override
public Blob getJPABlob(byte[] binaryData) throws ODataJPARuntimeException {
try {
return new JDBCBlob(binaryData);
} catch (SerialException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
} catch (SQLException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return null;
}
#Override
public Clob getJPAClob(char[] characterData) throws ODataJPARuntimeException {
try {
return new JDBCClob(new String(characterData));
} catch (SQLException e) {
ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e);
}
return null;
}
}
the only problem is I couldn't find any implementation for JDBCBlob and JDBCClob. Any suggestion about how can I implement them or use some classes?
If You are using MySQL it requires an additional ExceptionInterceptor along with the Blob Implementation. You can have a custom implementation of ExceptionInterceptor and use it to initialise the Blob field.
The code to achieve it would be as follows
import java.sql.Blob;
import java.sql.Clob;
import java.util.Properties;
import org.apache.olingo.odata2.jpa.processor.api.OnJPAWriteContent;
import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.log.Log;
public class CustomOnJPAWriteContent implements OnJPAWriteContent {
#Override
public Blob getJPABlob(byte[] binaryData) throws ODataJPARuntimeException {
return new com.mysql.cj.jdbc.Blob(binaryData, exceptionInterceptor);
}
#Override
public Clob getJPAClob(char[] characterData) throws ODataJPARuntimeException {
return new com.mysql.cj.jdbc.Clob(new String(characterData), exceptionInterceptor);
}
ExceptionInterceptor exceptionInterceptor = new ExceptionInterceptor() {
#Override
public Exception interceptException(Exception sqlEx) {
// TODO Auto-generated method stub
return null;
}
#Override
public ExceptionInterceptor init(Properties props, Log log) {
// TODO Auto-generated method stub
return null;
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
};
}

Need help on a simple server/multiple client chat application

this is the scenario .. i have 2 clients connected to a server.. i want them to be able to chat with eachother. After a couple of messages i get this error.
Exception in thread "Thread-0" java.lang.ClassCastException:
java.io.ObjectStreamClass cannot be cast to message.Mesaj
at server.ServerThread.readAndWrite(ServerThread.java:43)
at server.ServerThread.run(ServerThread.java:61)
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at server.ServerThread.readAndWrite(ServerThread.java:43)
at server.ServerThread.run(ServerThread.java:61)
This is the client:
package client;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import message.Mesaj;
public class Client {
public static int port=4321;
public static Socket socket;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Scanner sc;
public Client() throws IOException{
socket = new Socket ("localhost",4321);
oi = new ObjectInputStream(socket.getInputStream());
oo = new ObjectOutputStream(socket.getOutputStream());
}
public static void listen() throws ClassNotFoundException, IOException{
while(true){
Mesaj m = (Mesaj) oi.readObject();
if(m!=null){
System.out.println("mesajul este: " + m.getMesaj());
}
}
}
public static void write() throws IOException{
sc= new Scanner(System.in);
while(true){
String trimite= sc.nextLine();
Mesaj m = new Mesaj();
m.setMesaj(trimite);
oo.writeObject(m);
oo.flush();
}
}
public static Thread t = new Thread(){
public void run(){
try {
listen();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static Thread t2 = new Thread(){
public void run(){
try {
write();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static void main(String[] args) throws IOException{
new Client();
t.start();
t2.start();
}
This is the Server:
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server {
public int port;
public static Socket socket;
public static ServerSocket serverSocket;
public Server() throws IOException{
this.port=4321;
serverSocket = new ServerSocket(port);
}
public static void main (String [] args){
try {
new Server();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Server functionabil..asteptam conexiune client");
while(true){
try {
socket= serverSocket.accept();
ServerThread st= new ServerThread(socket);
st.start();
System.out.println("Conexiune realizata -client conectat");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
..and this is the Server Thread:
package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import message.Mesaj;
public class ServerThread extends Thread {
boolean running;
public static ObjectOutputStream oo;
public static ObjectInputStream oi;
public static Mesaj m;
public static Socket socket;
public ServerThread(Socket socket) throws ClassNotFoundException{
try {
running=true;
this.socket=socket;
oo = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readAndWrite() throws ClassNotFoundException, IOException{
oi = new ObjectInputStream(socket.getInputStream());
while(true){
m= (Mesaj) oi.readObject();
if(m!=null){
oo.writeObject(m);
oo.flush();
System.out.println(m.getMesaj());
}
}
}
public void run(){
System.out.println("Server Thread contectat");
try {
readAndWrite();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT:
This is the message class:
package message;
import java.io.Serializable;
public class Mesaj implements Serializable {
private String mesaj;
public String getMesaj() {
return mesaj;
}
public void setMesaj(String mesaj) {
this.mesaj = mesaj;
}
}
You having concurrency issues.
Both serverthreads access the same static outputstream, meaning that there is a change for corruption as Object streams aren't designed for this.
In ServerThread, remove static from all the variables and the method "readAndWrite".
public ObjectOutputStream oo;
public ObjectInputStream oi;
public Mesaj m;
public Socket socket;
...
public void readAndWrite() throws ClassNotFoundException, IOException{
If you want to access the output streams from multiple threads, you should synchronize on them.

Tomcat WebSocket connection closed, Code: 1006 issue

I'm trying Tomcat server with websocket. This is what I do:
I created 3 java files, copied from Tomcat examples. Please see the code below.
Then I build a war file and put it in webapps. But then I got this error message:
Info: WebSocket connection closed, Code: 1006
Do I miss any step to make a websocket on Tomcat?
Thanks.
1. ExamplesConfig.java
import java.util.HashSet;
import java.util.Set;
import javax.websocket.Endpoint;
import javax.websocket.server.ServerApplicationConfig;
import javax.websocket.server.ServerEndpointConfig;
public class ExamplesConfig implements ServerApplicationConfig
{
#Override
public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> scanned)
{
Set<ServerEndpointConfig> result = new HashSet<ServerEndpointConfig>();
System.out.println("ExamplesConfig ==========> getEndpointConfigs");
if (scanned.contains(EchoEndpoint.class))
{
result.add(ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/websocket/echoProgrammatic").build());
}
return result;
}
#Override
public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scanned)
{
// Deploy all WebSocket endpoints defined by annotations in the examples
// web application. Filter out all others to avoid issues when running
// tests on Gump
Set<Class<?>> results = new HashSet<Class<?>>();
for (Class<?> clazz : scanned)
{
if (clazz.getPackage().getName().startsWith("websocket."))
{
System.out.println("getAnnotatedEndpointClasses ===========>" + clazz);
results.add(clazz);
}
}
return results;
}
}
2. EchoEndpoint.java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
public class EchoEndpoint extends Endpoint
{
#Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
RemoteEndpoint.Basic remoteEndpointBasic = session.getBasicRemote();
session.addMessageHandler(new EchoMessageHandlerText(remoteEndpointBasic));
session.addMessageHandler(new EchoMessageHandlerBinary(remoteEndpointBasic));
}
private static class EchoMessageHandlerText
implements MessageHandler.Partial<String> {
private final RemoteEndpoint.Basic remoteEndpointBasic;
private EchoMessageHandlerText(RemoteEndpoint.Basic remoteEndpointBasic) {
this.remoteEndpointBasic = remoteEndpointBasic;
}
#Override
public void onMessage(String message, boolean last) {
try {
if (remoteEndpointBasic != null) {
remoteEndpointBasic.sendText(message, last);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static class EchoMessageHandlerBinary
implements MessageHandler.Partial<ByteBuffer> {
private final RemoteEndpoint.Basic remoteEndpointBasic;
private EchoMessageHandlerBinary(RemoteEndpoint.Basic remoteEndpointBasic) {
this.remoteEndpointBasic = remoteEndpointBasic;
}
#Override
public void onMessage(ByteBuffer message, boolean last) {
try {
if (remoteEndpointBasic != null) {
remoteEndpointBasic.sendBinary(message, last);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3. EchoAnnotation.java
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.OnMessage;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/websocket/echoAnnotation")
public class EchoAnnotation
{
#OnMessage
public void echoTextMessage(Session session, String msg, boolean last) {
try {
if (session.isOpen()) {
System.out.println("==========> this is my code");
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
#OnMessage
public void echoBinaryMessage(Session session, ByteBuffer bb,
boolean last) {
try {
if (session.isOpen()) {
session.getBasicRemote().sendBinary(bb, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) {
// Ignore
}
}
}
/**
* Process a received pong. This is a NO-OP.
*
* #param pm Ignored.
*/
#OnMessage
public void echoPongMessage(PongMessage pm) {
// NO-OP
}
}
This example work's fine with Tomcat 7.0.x if you are running JVM version 1.7 and your web.xml use Servlet Specification version 3.0 according to Tomcat documentation.
You web.xml file should look like this :
<web-app version="3.0" ... >

could not disconnect socket

Here is my tcpClient class:
import java.io.*;
import java.net.*;
public class tcpClient
{
private String _ip;
private int _port;
private Socket _clientSocket;
public tcpClient(String IP, int Port)
{
_ip = IP;
_port = Port;
}
public boolean createSocket()
{
boolean retSt = false;
try
{
_clientSocket = new Socket(this._ip, this._port);
retSt = true;
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return retSt;
}
public boolean disposeSocket()
{
boolean retSt = false;
try
{
_clientSocket.shutdownInput();
_clientSocket.shutdownOutput();
_clientSocket.close();
retSt = true;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return retSt;
}
public boolean isConnected()
{
return _clientSocket.isConnected();
}
}
Here is my main method:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
public class cos
{
public static void main(String[] args)
{
tcpClient client = new tcpClient("192.168.10.39", 1234);
client.createSocket();
System.out.println(client.isConnected());
client.disposeSocket();
System.out.println(client.isConnected());
client.createSocket();
System.out.println(client.isConnected());
client.disposeSocket();
System.out.println(client.isConnected());
}
}
Here is my console output:
true
true
true
true
Why couldn't i disconnect from server?
from java doc:
Note: Closing a socket doesn't clear its connection state, which means
this method will return true for a closed socket (see isClosed()) if
it was successfuly connected prior to being closed.

Cannot Start a Method In a Different Class Using a Library

I've just created my first library for an Android app I've built (I have code I need to reuse in the future across different apps) and I need to start a method I have in the main project from the library - however when I attempt to do so using the line:
com.project.sample.datasettings.UpdateActivity.success();
I'm getting a compiler error stating:
com.project.sample.UpdateActivity Cannot Be Resolved To A Type
SOURCE:
package com.project.sample.networktasklibrary;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import com.project.sample.networktasklibrary.XmlParserHandlerFinal;
import com.project.sample*;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
// this class performs the call to webservice in the background
public class NetworkTask extends AsyncTask<String, String, InputStream> {
private static final String LOG_TAG = "STDataSettings";
private static final String TAG_RESULT = "success";
private static InputStream stream;
#Override
protected InputStream doInBackground(String... params) {
try {
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected static synchronized InputStream getQueryResults(
String urlQueryString) throws IOException, SAXException,
SSLException, SocketTimeoutException, Exception {
Bundle queryResults = new Bundle();
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(50000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
try {
https = (HttpsURLConnection) urlo.openConnection();
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
}
String queryResult = null;
queryResults.putString(TAG_RESULT, queryResult);
return stream;
}
public InputStream getInputStream() {
return stream;
}
protected void onPostExecute(InputStream queryResults) {
// TODO Auto-generated method stub
super.onPostExecute(queryResults);
com.project.sample.datasettings.UpdateActivity.success();
}
}
UPDATE ACTIVITY CODE SAMPLE:
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
}
Have you ever tried to add the library to the main project?
Right click the Project name -> Property -> Android -> Add. Then choose the library project.

Categories

Resources