I wrote an applet which takes the MAC address from the local computer.
It works fine on eclipse but at the moment I try to run it via the browser it does not.
after some debugging i've come to realize that this part returns null on browser
InetAddress.getLocalHost();
Can anyone tell me why?
EDIT:
This is code I found somewhere on the web:
import java.applet.Applet;
import java.awt.Graphics;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class LoginApplet extends Applet {
private static final long serialVersionUID = 1L;
private String macAddress;
public void init() {
setMacAddress(getMacAddressFromClient());
}
public void paint(Graphics g)
{
String mac = getMacAddress();
if(mac.isEmpty())
{
mac = "Empty";
}
g.drawString(mac,15,15);
}
public String getMacAddressFromClient() {
String macAddr= "";
InetAddress addr;
try {
addr = InetAddress.getLocalHost();
macAddress += addr.getHostAddress();
NetworkInterface dir = NetworkInterface.getByInetAddress(addr);
byte[] dirMac = dir.getHardwareAddress();
int count=0;
for (int b:dirMac){
if (b<0) b=256+b;
if (b==0) {
macAddr=macAddr.concat("00");
}
if (b>0){
int a=b/16;
if (a==10) macAddr=macAddr.concat("A");
else if (a==11) macAddr=macAddr.concat("B");
else if (a==12) macAddr=macAddr.concat("C");
else if (a==13) macAddr=macAddr.concat("D");
else if (a==14) macAddr=macAddr.concat("E");
else if (a==15) macAddr=macAddr.concat("F");
else macAddr=macAddr.concat(String.valueOf(a));
a = (b%16);
if (a==10) macAddr=macAddr.concat("A");
else if (a==11) macAddr=macAddr.concat("B");
else if (a==12) macAddr=macAddr.concat("C");
else if (a==13) macAddr=macAddr.concat("D");
else if (a==14) macAddr=macAddr.concat("E");
else if (a==15) macAddr=macAddr.concat("F");
else macAddr=macAddr.concat(String.valueOf(a));
}
if (count<dirMac.length-1)macAddr=macAddr.concat("-");
count++;
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
macAddr=e.getMessage();
} catch (SocketException e) {
// TODO Auto-generated catch block
macAddr = e.getMessage();
}
return macAddr;
}
public String getMacAddress() {
return macAddress;
}
public void setMacAddress(String macAddress) {
this.macAddress += macAddress;
}
}
In eclipse: addr has the localhost address
In the browser (IE and chrome) addr is null.
Related
I am trying to write a multi-threaded server program with 2 servers.I am testing with 2 clients.Sometimes depending on a md5 hashcode a client connected to a server has to disconnect from said server and connect to the other one.Sometimes this happens without any problems and sometimes I get java.net.SocketException: Socket closed.Here s the code
Broker class(Server):
import java.io.IOException;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;
import java.util.ArrayList;
import java.util.List;
public class Broker extends Node implements Runnable {
private static List<Publisher> registeredpublishers = new ArrayList<Publisher>();
private static List<Consumer> registeredConsumers = new ArrayList<Consumer>();
public static List<Consumer> GetConsumers(){
return registeredConsumers;
}
public String Name;
public Integer port;
public Broker(Integer port,String name){
this.port=port;
this.Name=name;
}
ServerSocket providerSocket;
Socket connection = null;
String ip="127.0.0.1";
BigInteger myKeys;
public void run(){
calculateKeys();
Node.getBrokers().add(this);
openServer();
}
void calculateKeys(){
String g =ip+ (port != null ? port.toString() : null);
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
m.reset();
m.update(g.getBytes());
byte[] digest = m.digest();
myKeys = new BigInteger(1,digest);
BigInteger a=new BigInteger("25");
myKeys=myKeys.mod(a);
System.out.println(myKeys);
}
void openServer()throws NullPointerException {
try {
providerSocket = new ServerSocket(this.port, 10);
while (true) {
acceptConnection();
new BrokerHandler(connection,this).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
providerSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void acceptConnection()throws NullPointerException {
try {
connection = providerSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("client connected.");
{
}
}
public static void main(String args[]) {
new Thread(new Broker(54319,"First")).start();
new Thread(new Broker(12320,"Second")).start();
}
}
BrokerHandler Class
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigInteger;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class BrokerHandler extends Thread implements Serializable {
ObjectInputStream in;
ObjectOutputStream out;
String f;
BigInteger theirKeys;
Broker broker;
Object e;
Message request;
public BrokerHandler(Socket connection,Broker broker) throws NullPointerException{
try {
in = new ObjectInputStream(connection.getInputStream());
out =new ObjectOutputStream(connection.getOutputStream());
try {
this.request=(Message)in.readObject();
this.f=request.artist;
this.e =request.entity;
this.broker=broker;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
if(this.e instanceof Consumer){
calculateMessageKeys(this.request);
checkBroker(this.broker,(Consumer) e);
}
}
public synchronized void disconnect(Socket connection){
try {
in.close();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}finally {
try {
connection.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void checkBroker(Broker broker,Consumer consumer) {
int intMyKeys = broker.myKeys.intValue();
int intTheirKeys = theirKeys.intValue();
if (intTheirKeys > 23) {
intTheirKeys = intTheirKeys % 23;
}
if (intTheirKeys <= intMyKeys && intTheirKeys >= intMyKeys - 11) {
consumer.Register(broker, f);
System.out.println(broker.Name + "Client Connected and Registered");
} else {
int thePort = 0;
System.out.println(broker.Name + "Client changing server");
for (Broker broker1 : Node.getBrokers()) {
int KEYS = broker1.myKeys.intValue();
if (intTheirKeys <= KEYS && intTheirKeys >= KEYS - 11) {
thePort = broker1.port;
System.out.println(thePort);
}
}
disconnect(broker.connection);
Consumer a = new Consumer(consumer.artist, thePort);
new ConsumerHandler(a).start();
}
}
public void calculateMessageKeys(Message request) {
MessageDigest m = null;
try {
m = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
m.reset();
m.update(f.getBytes());
byte[] digest = m.digest();
theirKeys = new BigInteger(1,digest);
BigInteger mod=new BigInteger("25");
theirKeys=theirKeys.mod(mod);
System.out.println(theirKeys);
}
}
Consumer class
import java.io.*;
import java.util.Random;
public class Consumer extends Node implements Serializable {
String artist;
Random r=new Random();
int max=12320;
int min=54319;
int port;
Message request;
public Consumer(String artist){
this.artist=artist;
this.port=new Random().nextBoolean() ? max : min;
request= new Message(artist,this.getConsumer());
}
public Consumer(String artist,int port){
this.artist=artist;
this.port=port;
request= new Message(artist,this.getConsumer());
}
public Consumer getConsumer(){
return this;
}
public void Register(Broker broker,String ArtistName){
broker.GetConsumers().add(this);
System.out.println(this.artist);
}
}
ConsumerHandle Class
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ConsumerHandler extends Thread{
Consumer consumer;
public ConsumerHandler(Consumer consumer){
this.consumer=consumer;
}
void connect(int port) {
Socket requestSocket=null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
try {
requestSocket = new Socket("127.0.0.1", consumer.port);
out = new ObjectOutputStream(requestSocket.getOutputStream());
in = new ObjectInputStream(requestSocket.getInputStream());
System.out.println("Message created.");
out.writeObject(consumer.request);
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
try {
in.close();
out.close();
requestSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
public void run(){
connect(consumer.port);
}
public static void main(String args[]) {
Consumer a=new Consumer("Kevin MacLeod");
Consumer b=new Consumer("Alexander Narakada");
new ConsumerHandler(a).start();
new ConsumerHandler(b).start();
}
}
and the stack trace of when it happens:
java.net.SocketException: Socket closed
at java.base/sun.nio.ch.NioSocketImpl.ensureOpenAndConnected(NioSocketImpl.java:166)
at java.base/sun.nio.ch.NioSocketImpl.beginRead(NioSocketImpl.java:232)
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:300)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:351)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:802)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:937)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:932)
at java.base/java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2778)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:3105)
at java.base/java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:3115)
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1597)
at java.base/java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2410)
at java.base/java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2304)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2142)
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1646)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:464)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at BrokerHandler.<init>(BrokerHandler.java:26)
at Broker.openServer(Broker.java:59)
at Broker.run(Broker.java:34)
at java.base/java.lang.Thread.run(Thread.java:830)
import javax.swing.*;
import java.io.Serializable;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server implements Serializable{
public static void main(String[] args) {
String test1= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
int portnumber = tryParse(test1);
if (portnumber !=0) {
try {
Registry reg = LocateRegistry.createRegistry(portnumber); //Creates and exports a Registry instance on the local host that accepts requests
RmiImplementation imp = new RmiImplementation("C://ServerStorage");
reg.bind("remoteObject", imp);
System.out.println("Server is ready.");
System.out.println(portnumber);
} catch (Exception e) {
System.out.println("Server failed: " + e);
}
}
}
private static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (Exception e) {
return 0;
}
}
}
The above code helps me to set up my file server.
when the application is run, the dialog port number is requested.
If I type letters instead of numbers the program stops running, but I want it to continue and show me the dialog again.
Try with a do-while,
int portnumber = 0;
do {
String text= JOptionPane.showInputDialog(null,"Port(0-65535):","Port",JOptionPane.QUESTION_MESSAGE);
portnumber = tryParse(text);
}while(portnumber==0);
I need some help with a IllegalStateException in Java.
I got a sourcecode that should read out Data from a USB Device.
That code is not finished yet, but I already got the following error report
Exception in thread "main" java.lang.IllegalStateException: default context is not initialized at org.usb4java.Libusb.exit(Native Method) at testnew.main(testnew.java:122)
Line 122 is LibUsb.exit(null)
Code is below
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.usb.UsbConfiguration;
import javax.usb.UsbDevice;
import javax.usb.UsbDeviceDescriptor;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import javax.usb.UsbHostManager;
import javax.usb.UsbHub;
import javax.usb.UsbInterface;
import javax.usb.UsbInterfacePolicy;
import javax.usb.UsbNotActiveException;
import javax.usb.event.UsbPipeDataEvent;
import javax.usb.event.UsbPipeErrorEvent;
import javax.usb.event.UsbPipeListener;
import org.usb4java.BufferUtils;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
public class testnew {
private final static short VENDOR_ID = 0x0403;
private final static short PRODUCT_ID = 0x6001;
private static byte IN_ENDPOINT = (byte) 0x81;
private static long TIMEOUT = 5000;
private final static int INTERFACE = 0;
private final static Object CONNECT_HEADER = 000;
private final static Object CONNECT_BODY = 000;
public static UsbDevice getHygrometerDevice(UsbHub hub) {
UsbDevice launcher = null;
for (Object object : hub.getAttachedUsbDevices()) {
UsbDevice device = (UsbDevice) object;
if (device.isUsbHub()) {
launcher = getHygrometerDevice((UsbHub) device);
if (launcher != null)
return launcher;
} else {
UsbDeviceDescriptor desc = device.getUsbDeviceDescriptor();
if (desc.idVendor() == VENDOR_ID && desc.idProduct() == PRODUCT_ID)
return device;
}
}
return null;
}
public static char readKey() {
try {
String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
if (line.length() > 0)
return line.charAt(0);
return 0;
} catch (IOException e) {
throw new RuntimeException("Unable to read key", e);
}
}
public static ByteBuffer read(DeviceHandle handle, int size) {
ByteBuffer buffer = BufferUtils.allocateByteBuffer(size).order(ByteOrder.LITTLE_ENDIAN);
IntBuffer transferred = BufferUtils.allocateIntBuffer();
int result = LibUsb.bulkTransfer(handle, IN_ENDPOINT, buffer, transferred, TIMEOUT);
if (result != LibUsb.SUCCESS) {
throw new LibUsbException("Unable to read data", result);
}
System.out.println(transferred.get() + " bytes read from device");
return buffer;
}
public static void main(String[] args) {
// Search for the missile launcher USB device and stop when not found
UsbDevice device;
try {
device = getHygrometerDevice(UsbHostManager.getUsbServices().getRootUsbHub());
if (device == null) {
System.err.println("Missile launcher not found.");
System.exit(1);
return;
}
// Claim the interface
UsbConfiguration configuration = device.getUsbConfiguration((byte) 1);
UsbInterface iface = configuration.getUsbInterface((byte) INTERFACE);
iface.claim(new UsbInterfacePolicy() {
#Override
public boolean forceClaim(UsbInterface usbInterface) {
return true;
}
});
iface.getUsbEndpoint(IN_ENDPOINT).getUsbPipe().addUsbPipeListener(new UsbPipeListener() {
#Override
public void errorEventOccurred(UsbPipeErrorEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void dataEventOccurred(UsbPipeDataEvent arg0) {
for (byte b : arg0.getData())
System.out.print(b);
System.out.print("\n");
}
});
;
} catch (UsbNotActiveException | UsbDisconnectedException | UsbException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Deinitialize the libusb context
LibUsb.exit(null);
}
}
Any suggestions?
you did not initialize the context this is why you get the error when you try to deinitialize it, see http://www.programcreek.com/java-api-examples/index.php?api=org.usb4javaLibUsb example 17
public static void main(String[] args)
{
//Initialize the libusb context
int result = LibUsb.Init(null);
if (result != LibUsb.SUCCESS){
throw new LibUsbException("Unable to initialze libusb",result);
}
[...]
how to open the pipe depends on what transfer type you want to choose (bulk transfer, sychronous transfer, asynchronous transfer), see http://usb4java.org/quickstart/javax-usb.html
for synchronous transfer you can use (copied from http://usb4java.org/quickstart/javax-usb.html)
UsbEndpoint endpoint = iface.getUsbEndpoint((byte) 0x83);
UsbPipe pipe = endpoint.getUsbPipe();
pipe.open();
try
{
byte[] data = new byte[8];
int received = pipe.syncSubmit(data);
System.out.println(received + " bytes received");
}
finally
{
pipe.close();
}
There are IN endpoints and OUT endpoints, you write to OUT and read from IN. Control transfers go to EP0. All USB communication is initiated by the host device, meaning the USB device can not even initiate a communication.
for deeper information on USB protocol see http://www.beyondlogic.org/usbnutshell/usb1.shtml
i am trying to do java database connectivity in eclipse juno using eclipse but i am getting the following error comes
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
suggest me some solutions..........
this is my code :
package example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Connect {
public static Connection getConnection()
{
String url="jdbc:mysql://localhost:3306/demo";
String drive="com.mysql.jdbc.Driver";
//String databse="demo";
String user="root";
String password="abc";
Connection conn=null;
try
{
Class.forName(drive);
conn=DriverManager.getConnection(url, user, password);
}
catch (Exception e)
{
System.out.println(""+e);
}
return conn;
}
public static void main(String[] args)
{
Connection conn=null;
PreparedStatement pstmt=null;
try
{
conn=getConnection();
conn.setAutoCommit(false);
pstmt=conn.prepareStatement("insert into testlongtele(address,name)values(?,?)");
pstmt.setString(0, "NIRAV");
pstmt.setString(1, "KAMANI");
pstmt.executeUpdate();
pstmt.close();
conn.commit();
conn.close();
}
catch(Exception e)
{
System.out.println(""+e);
}
}
}
From This link:
Possible Cause of this error is:
1) You don't have mysql-connector.jar in your Classpath. as stated earlier this jar file contains "com.mysql.jdbc.Driver" class it must be present in classpath in order to successful connection to mysql database. you can downlad mysql-connector.jar from mysql.com.
2) mysql-connector.jar is in your classpath but somehow your classpath is getting overridden.
Classpath is tricky in Java and classpath specified in jar may override CLASSPATH path variable. See how classpath works in Java to understand this issue in detail.
3) mysql-connector.jar is in classpath but current user doesn't have read permission.
This problem often happens in Unix or Linux operating system which has sophisticated file and directory permission based on user, group and owner level. just get the right permission and run your program again.
You can add:
class.forName(driver).newInstance();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mindtree.kalinga.exception.ConnectionfailedException;
public class JdbcConnection {
private static JdbcConnection jdbcConnection;
private static Connection dbConnection;
private JdbcConnection() {
}
public static JdbcConnection getInstance() {
if (jdbcConnection == null)
jdbcConnection = new JdbcConnection();
return jdbcConnection;
}
public static void createConnection() throws ConnectionfailedException {
try {
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mindtree", "root", "Welcome123");
} catch (SQLException e) {
throw new ConnectionfailedException("Error creating the connection to database", e);
}
System.out.println("Connection to db Established!");
}
public static Connection getConnection() {
return dbConnection;
}
public static void closeConnection() throws ConnectionfailedException {
try {
dbConnection.close();
} catch (SQLException e) {
throw new ConnectionfailedException("connection not closed properly", e);
}
}
}
--------------------------------------
Main
--------------------------------------
package com.mindtree.kalinga.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.exception.ConnectionfailedException;
import com.mindtree.kalinga.service.Mindtreeservice;
import com.mindtree.kalinga.serviceimp.Mindtreeserviceimp;
import com.mindtree.kalinga.utility.JdbcConnection;
public class MindtreeMain {
static Scanner in = new Scanner(System.in);
static Mindtreeservice ms = new Mindtreeserviceimp();
public static void main(String[] args) {
try {
JdbcConnection.createConnection();
} catch (ConnectionfailedException e) {
System.out.println("Not able to connect to database! Terminating application!");
e.printStackTrace();
}
MindtreeMain mm = new MindtreeMain();
int i = 1;
while (i == 1) {
System.out.println("1. to enter the detail\n" + "2. fetch the detail\n" + "3. to exit");
int key = in.nextInt();
switch (key) {
case 1:
Mindtree m = mm.createminds();
break;
case 2:
List<Mindtree> ml = new ArrayList<>();
mm.display(ml);
break;
case 3:
i = 0;
break;
default:
break;
}
}
}
private Mindtree createminds() {
// TODO Auto-generated method stub
System.out.println("enter the id of mind");
int id = in.nextInt();
in.nextLine();
System.out.println("enter the name of mind");
String name = in.nextLine();
System.out.println("ente the address of minds");
String address = in.nextLine();
Mindtree m = new Mindtree(id, name, address);
return m;
}
private void display(List<Mindtree> mind) {
for (Mindtree i : mind) {
System.out.println(i.getMid());
System.out.println(i.getName());
System.out.println(i.getAddress());
}
}
}
-------------------------------------------------
service
-------------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreeservice {
public void insertmind(Mindtree m);
public List<Mindtree> getAllminds();
}
---------------------------------------------
serviceimp
---------------------------------------------
package com.mindtree.kalinga.serviceimp;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.daoimp.Mindtreedaoimp;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.service.Mindtreeservice;
public class Mindtreeserviceimp implements Mindtreeservice {
Mindtreedao md = new Mindtreedaoimp();
#Override
public void insertmind(Mindtree m) {
// TODO Auto-generated method stub
md.insertMindToDb(m);
}
#Override
public List<Mindtree> getAllminds() {
// TODO Auto-generated method stub
return md.getAllMindFromDb();
}
}
--------------------------------------------
dao
--------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreedao {
public void insertMindToDb(Mindtree m);
public List<Mindtree> getAllMindFromDb();
}
-------------------------------------------
daoimp
-------------------------------------------
package com.mindtree.kalinga.daoimp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.utility.JdbcConnection;
import com.mysql.jdbc.Statement;
public class Mindtreedaoimp implements Mindtreedao {
#Override
public void insertMindToDb(Mindtree m) {
Connection con = JdbcConnection.getConnection();
String query = "insert into mindtree values(?,?,?);";
PreparedStatement ps = null;
try {
ps = con.prepareStatement(query);
ps.setInt(1, m.getMid());
ps.setString(2, m.getName());
ps.setString(3, m.getAddress());
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
#Override
public List<Mindtree> getAllMindFromDb() {
// TODO Auto-generated method stub
List<Mindtree> mtl = new ArrayList<Mindtree>();
Connection con = JdbcConnection.getConnection();
String query = "select * from mindtree;";
Statement st = null;
ResultSet rs = null;
try {
st = (Statement) con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
Mindtree m = new Mindtree(rs.getInt(1), rs.getString(2), rs.getString(3));
mtl.add(m);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mtl;
}
}
-----------------------------------------------
exception
package com.mindtree.kalinga.exception;
public class ConnectionfailedException extends Exception {
public ConnectionfailedException() {
super();
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
-----------------------------
entity
-----------------------------
package com.mindtree.kalinga.entity;
public class Mindtree {
int Mid;
String name;
String address;
public Mindtree(int mid, String name, String address)
{
Mid = mid;
this.name = name;
this.address = address;
}
public int getMid() {
return Mid;
}
public void setMid(int mid) {
Mid = mid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
I have a the necessary RMI classes created, The client can send a message and it gets printed in the server window.
On the server i would like to read the message and for example if the message is equal to 100 then print out a message.
The problem being when i run the server i immediately get a null pointer exception. When i send the message 100 from the client to the server it prints the message but wont execute the if statement.
Interface:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface FileInterface extends Remote {
void message(String message) throws RemoteException;
}
Implementation:
import java.io.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class FileImpl extends UnicastRemoteObject implements FileInterface {
private String name;
public FileImpl(String s) throws RemoteException {
super();
name = s;
}
public void message(String message) throws RemoteException{
System.out.println(message);
}
} catch(Exception e) {
System.err.println("FileServer exception: "+ e.getMessage());
e.printStackTrace();
return(null);
}
}
}
Client:
import java.io.*;
import java.rmi.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
public class FileClient{
public static boolean loggedIn = false;
public static void main(String argv[]) {
try {
int RMIPort;
String hostName;
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
System.out.println("Enter the RMIRegistry host namer:");
hostName = br.readLine();
if( hostName.length() == 0 ) // if user did not enter a name
hostName = "localhost"; // use the default host name
System.out.println("Enter the RMIregistry port number:");
String portNum = br.readLine();
if( portNum.length() == 0 )
portNum = "1097"; // default port number
RMIPort = Integer.parseInt(portNum);
String registryURL = "rmi://" + hostName+ ":" + portNum + "/FileServer";
// find the remote object and cast it to an interface object
FileInterface fi = (FileInterface) Naming.lookup(registryURL);
System.out.println("Lookup completed " );
//System.out.println("File " + argv[0] + " Transfered" );
// invoke the remote method
boolean done = false;
//file.getName()
while( !done ) {
System.out.println("Enter Code: 100 = Login, 200 = Upload, 300 = Download, 400 = Logout: ");
String message = br.readLine();
boolean messageOK = false;
if( message.equals("100") ) {
messageOK = true;
System.out.println("Enter T-Number: (Use Uppercase 'T')");
String login = br.readLine();
if( login.charAt(0) == 'T' ) {
loggedIn = true;
fi.message("100");
System.out.println("Login Successful");
continue;
} else {
System.out.println("Login Error");
continue;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Server:
import java.io.*;
import java.rmi.*;
public class FileServer {
public static void main(String argv[]) {
if(System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
FileInterface fi = new FileImpl("FileServer");
Naming.rebind("//localhost:1097/FileServer", fi);
System.out.println("Server Started...");
boolean done = false;
while( !done ) {
if ((msg.trim()).equals("100")) {
System.out.println("message recieved: 100 logged in");
} else {
System.out.println("Login Error");
}
}
} catch(Exception e) {
System.out.println("FileServer: "+e.getMessage());
e.printStackTrace();
}
}
}
Any help here would be appreciated.