Facing null pointer Exception in at RpcMap? - java

I am trying to read a serialized DTO at server side object from file, i can read it without any exception but after some exception throws when rpc replies to client side
java.lang.NullPointerException
at com.extjs.gxt.ui.client.data.RpcMap.size(RpcMap.java:198)
what is the issue?
i m using GXT 2.2.5.
here is a server side code
public List<ShellCommand> getCommands(String user, String platform)
throws CVSServiceException {
readFromFile();
if(commands.isEmpty())
return null;
else
return commands;
}
private void readFromFile(){
File readFile = new File(DIR, SHELLCOMMAND);
if(readFile.exists()){
try{
InputStream file = new FileInputStream(readFile);
InputStream buffer = new BufferedInputStream( file );
ObjectInput input = new ObjectInputStream ( buffer );
try{
commands = (List<ShellCommand>) input.readObject();
} catch(Exception e){
e.printStackTrace();
} finally{
input.close();
}
} catch(Exception e){
e.printStackTrace();
}
}
i can read and feel my list commands perfactly but then after calling getcommands() from client side it throws this error causes my RPC call to fail?

Related

blocking IO method throw NoSuchException in while loop - Java

I am new to socket programming and not very familiar with I/O class.
In the following codes, I am making a simple socket program and use while loop to make it able to accept clientSocket for more than one time. The codes were executed well in the first iteration while throws NoSuchElementException when it reaches header = in.nextLine() (in the run method of the thread). I thought the method is blocking and should wait for the input? Similar things happen when I call next().
Can anyone help me understand this? I will greatly appreciate it!
public static void main(String args[]) throws IOException {
Socket clientSocket = null;
ServerSocket listenSocket = new ServerSocket(8888);
int num = 0;
try {
while (true) {
clientSocket = listenSocket.accept();
new ClientSocket(clientSocket, num++).start();
}
} finally {
listenSocket.close();
}
}
private static class ClientSocket extends Thread {
private Socket socket;
private int numOfSocket;
public ClientSocket(Socket s, int num) {
socket = s;
numOfSocket = num;
}
public void run() {
//get file location
String header;
String fileLocation = null;
Scanner in = null;
Scanner scanner = null;
PrintWriter out = null;
try {
// Get header && extract file location
in = new Scanner(socket.getInputStream());
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
header = in.nextLine();
System.out.println(header);
String[] headerArr = header.split(" ");
String url = headerArr[1];
fileLocation = url.substring(1);
System.out.println(fileLocation);
// Try to get the file
FileInputStream file = new FileInputStream(fileLocation);
System.out.println("file found");
out.println("HTTP/1.1 200 OK\n");
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
}
out.flush();
} catch (FileNotFoundException e) {
System.out.print("file not found");
out.println("HTTP/1.1 404 File not found\n");
try {
scanner = new Scanner(new File("fileNotFound.html"));
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
}
out.flush();
} catch (FileNotFoundException a) {
System.out.println(a.getMessage());
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
in.close();
out.close();
if (scanner != null) {
scanner.close();
}
try {
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
More Clarifications:
So I ran it in Netbeans IDE and used a Chrome browser as a client to test it. It worked well in the first few attempts and then started to throw exceptions. The client is not affected and can still get the correct response. Just the server side is affected. Here is the message from the console.
Blockquote
GET /hah HTTP/1.1
hah
file not foundGET /favicon.ico HTTP/1.1
favicon.ico
file not foundGET /test.html HTTP/1.1
test.html
file found
Exception in thread "Thread-3" Exception in thread "Thread-5" Exception
in thread "Thread-4" java.util.NoSuchElementException: No line found
Blockquote
So eventually I figured out. It was the problem of the client(which was the Chrome browser)
When Chrome was visiting my server, it was actually sending 2 request. With one of my original request and the other is generated automatically to fetch meta data. Since my server is a simple and for educational purpose, it was not designed to handle errors not expected.
So the conclusion is that the codes works fine for its original purpose, but needs to be more robust in practical situations.

How to determine if a file is empty without getting EOFException

I'm trying to create a file called manager.txt and read it. If it is empty (which it is) it will call a method to add things into it but I keep getting EOFException. I know the file is empty but it's just a part of a programI'm working on. How to determine a file is empty without getting EOFException
try(ObjectOutputStream outManager = new ObjectOutputStream(new
FileOutputStream("manager.txt"))){
try(ObjectInputStream inManager = new ObjectInputStream(new
FileInputStream("manager.txt"))){
while(true){
manager.add((Manager)inManager.readObject());
if(manager.isEmpty()){
//A method to add
}
}catch(IOException e){
}
}catch (IOException e){
}
You can read from file as follows:
try (FileInputStream fis = new FileInputStream("manager.txt");
ObjectInputStream ois = new ObjectInputStream(fis);)
{
while (fis.available() > 0) {
Object obj = ois.readObject();
if (obj instanceof Manager) {
Manager manager = (Manager) obj;
System.out.println(manager);
}
}
} catch (IOException | ClassNotFoundException ex) {
ex.printStackTrace();
}
Basically, what you are looking for is fis.available().

ftp connection to determine if file is there

I am trying to check if the file exist in the FTP. When testing with one user it seems to be fine. But with the scenario of multiple users it seems to throw the below exception :
Exception in thread "main" sun.net.ftp.FtpProtocolException: Welcome message: 421.
Below is the code which we use to check if file is there and we have closed all the connection but still it throws sun.net.ftp.FtpProtocolException:Welcome message: 421.
public boolean getFtpFileExists(String fileUrl)
{
URL theURL = null;
InputStream inputStream = null;
FtpURLConnection ftpUrlConn = null;
boolean ftpFileExists = false;
try
{
theURL = new URL(fileUrl);
ftpUrlConn = (FtpURLConnection)theURL.openConnection();
inputStream = ftpUrlConn.getInputStream();//calling this method will throw a 'FileNotFoundException' if doesn't exist
ftpFileExists = true;
}
catch(FileNotFoundException fnfe)
{
ftpFileExists = false;
}
catch(Exception e)
{
System.out.println(e.toString());
ftpFileExists = false;//hmm, not sure really!
}
finally
{
//close inputStream & connection
if(inputStream != null)
{
try
{
inputStream.close();
}
catch(IOException ioe)
{
System.out.println("Error closing input stream: "+ioe.getMessage());
}
}
try
{
ftpUrlConn.close();
}
catch(Exception e)
{
System.out.println("Error closing ftpUrlConnection");
}
}
return ftpFileExists;
}
could anyone help me please?
Can you recreate the error that you get ?
at any case:
by the error MSG:
421: Service not available, closing control connection. This may be a
reply to any command if the service knows it must shut down.
It sounds like that maybe there's a configuration needs to be done at the FTPServer rather than a code error.

Where and when should I use the close() method to avoid IOException in ObjectInputStream?

I'm trying to read an object from client program over tcp. As you can see in this line I created objectInput:
ObjectInputStream objectInput = new ObjectInputStream(incoming.getInputStream());
And then read my input from the other program. It used to work fine until i made minor changes to clean up the program. Personally Assume I added
objectInput.clsoe();
My question is, After reading the object should I close the objectInputStream or Keep remain without close? Should I close it straight away after using it or at the end of if block or at the end of program? What are the effect of the close? By the way I have read the close documentation.
Here is the error:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2280)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2749)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:779)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
at Server.ClientWorker.run(MyCollectionServer.java:116)
at java.lang.Thread.run(Thread.java:680)
Here is my code:
public static void main(String[] args) {
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(port);
}
catch (IOException e)
{
e.printStackTrace();
}
while(true)
{
ClientWorker w;
try
{
w = new ClientWorker(serverSocket.accept());
Thread t = new Thread(w);
t.start();
}
catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
}
class ClientWorker implements Runnable
{
.....
private Socket incoming;
public ClientWorker(Socket incoming)
{
myList = new ArrayList<PureAlbum>();
loadList();
this.incoming = incoming;
}
.....
public synchronized void run()
{
else if(request.compareTo("AddAlbum")==0)
{
try
{
ObjectInputStream objectInput = new ObjectInputStream(incoming.getInputStream()); //This is the line mentioned in the error
PureAlbum object = (PureAlbum) objectInput.readObject();
if(object instanceof CDAlbum)
{
CDAlbum a = (CDAlbum) object;
myList.add(a);
System.out.println("Artist = " + a.getArtist());
}
else if(object instanceof Client.au.edu.uow.Collection.DVDAlbum)
{
myList.add((DVDAlbum) object);
}
else
{
System.err.println("Warning : The object to add to database is unknown! "+ object.getClass() + "*");
System.exit(0);
}
}
catch (UnknownHostException e)
{
System.err.println("Can not read the host name");
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("Can not read the FILE name"); //This exception has been called
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
Your code fragment is pretty long, so I will try to give you a general answer and it will hopefully help you.
The typical patterns of usage of stream.close() prior to java 7 are:
InputStream in = null;
try {
InputStream in = .....; // create your input stream;
// use input stream
} catch (IOException e) {
// do what you need here
} finally {
if (in != null) {
in.close();
}
}
or simply declare the method as throws IOException and then write:
InputStream in = null;
try {
InputStream in = .....; // create your input stream;
// use input stream
} finally {
if (in != null) {
in.close();
}
}
Pay atention that this example does not contain catch section.
Starting from java 7 we can enjoy the new facilities of the language:
try (
InputStream in = .....; // create your input stream;
) {
// use input stream
}
You even do not have to call close() at all. All resources defined into header of try block that implement interface Closable will be closed automatically.
This line of stack trace shows that the exception is occurring when you are initializing the ObjectInputStream, not when you are closing.
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:279)
The most likely cause is that the remote client did not open an ObjectOutputStream. It might have written some other kind of data, or it might have closed its output stream or simply exited.
You should close the Stream when you have completed your reading or writing.
here in this case , you should close the InputStream when you have read the file completely and you no longer require to read file from stream.
In Short , You should close the Stream when its work is over.
It may be in the end of program or after if loop....depends on your use case.
Hope this will help.
I am doing it this way (different example):
private void readFile() throws Exception {
FileInputStream fis = null;
ObjectInputStream ois = null;
Object aux = null;
try {
fis = new FileInputStream("lib.dat");
ois = new ObjectInputStream(fis);
do {
aux = ois.readObject();
if (aux instanceof MyObject)
this.myObjectInstance.add((MyObject) aux);
} while (true);
} catch (EOFException e) {
ois.close();
}
}
This way I am sending any relevant "Error" Exception upstairs to be handled, and once the EndOfFileException is launched this is specifically captured to close the stream properly.
The object has to be defined outside the Try block to be accessible from the Catch block.
The close() method could as well throw an IOException and this can't be caught by our Try block, this would have to be passed by the generic "throw Exception" of readFile() method.

Send a String[] array over Socket connection

So I'm trying to send a String[] over an open socket connection. I currently have this code:
Sending:
public void sendData() {
try {
OutputStream socketStream = socket.getOutputStream();
ObjectOutputStream objectOutput = new ObjectOutputStream(socketStream);
objectOutput.writeObject(new String[] {"Test", "Test2", "Test3"});
objectOutput.close();
socketStream.close();
} catch (Exception e) {
System.out.println(e.toString());
}
}
Recieving:
public Object readData() {
try {
InputStream socketStream = socket.getInputStream();
ObjectInputStream objectInput = new ObjectInputStream(new GZIPInputStream(socketStream));
Object a = objectInput.readObject();
return a;
} catch(Exception e) {
return null;
}
}
After I have recieved the String[] on the other end I want to be able to iterate through it like I would do normally so I can get the values. My current code doesn't seem to works as it returns null as the value.
Is this possible?
My current code doesn't seem to works as it returns null as the value.
And it is pretty obvious why too!
} catch(Exception e) {
return null;
}
That says "if something goes wrong, return null and don't tell me what the problem was"!
Catching and squashing exceptions like that is BAD PRACTICE. At the very least, you should try to print an exception stacktrace. In the writer code, you do this:
System.out.println(e.toString());
That is better than nothing, but it just prints the exception name and message. You should really be printing the full stacktrace ... like this:
e.printStackTrace(System.out);
And for production quality code, you should probably be LOGGING the exception, not just writing a message to standard output.
Once you have the stack trace, you can figure out what the real problem is and fix it.
I managed to figure it out on my own, I changed my recieving code to this:
public String[][] readData() {
try {
InputStream is = socket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
return (String[][])ois.readObject();
} catch(Exception e) {
return null;
}
}
Works like a charm now. Thanks all!

Categories

Resources