Combine to JSON HTTP POST requests? - java

I am a starting programmer, and for school I have to make a servlet, and an Android app.
A server sends a request to my servlet with JSON like this:
{
"function":"authenticate",
"requestId":"[random]",
"deviceId":"[android deviceid]",
"serviceType":"GCM"
}
The servlet reads the JSON and uses authenticateRequest() to send the notification:
else if(function.equals("authenticate"))
{
// Get the deviceId
String deviceId = jsonRequest.getDeviceId();
// Get the serviceType
String serviceType = jsonRequest.getServiceType();
GCM gcmClass = new GCM();
// Send authentication request to the user
int authenticationResult = 0;
if(serviceType.equals("GCM"))
{
authenticationResult = gcmClass.authenticateRequest(deviceId, requestId);
}
if(serviceType.equals("APNS"))
authenticationResult = 70000;
// Set the result field
jsonResponse.setResult(authenticationResult);
// Set the result text
if(authenticationResult == 0)
{
jsonResponse.setResultText("OK");
}
else if(serviceType.equals(10000))
{
jsonResponse.setResultText("DENY");
}
else if(serviceType.equals(70000))
{
jsonResponse.setResultText("Unsupported");
}
else
{
jsonResponse.setResult(50000);
}
// Set the requestId field
jsonResponse.setRequestId(requestId);
// Send the JSON response
response.getOutputStream().print(gson.toJson(jsonResponse));
response.getOutputStream().flush();
}
authenticateRequest (at this point it always says status 0 (which means always ALLOW):
public int authenticateRequest(String regId, String requestId)
{
try
{
String messageText = "New authentication request received!";
Sender sender = new Sender(Config.GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(30).delayWhileIdle(true).addData(Config.MESSAGE_KEY, messageText).addData("requestid", requestId).build();
result = sender.send(message, regId, 1);
return 0;
}
catch(Exception e) {
e.printStackTrace();
return 60000;
}
}
Now the Android app receives the requestId and I am able to use that to send another JSON HTTP POST request to the servlet.
The android app needs to send an ALLOW of DENY to the servlet and the servlet should return that in the same session as the first request was received.
But I can't seem to figure out how to do this, been stuck at this point a couple of days now.
I would be very grateful is someone could help me with this.

I found the answer myself! :D
This is what I was looking for:
class Authenticate {
boolean flag = true;
String finalUserInput = null;
public synchronized String sendAuthentication(String deviceId, String requestId)
{
// Send notification
GCM gcmClass = new GCM();
gcmClass.authenticateRequest(deviceId, requestId);
while(flag)
{
try
{
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
flag = true;
notify();
return finalUserInput;
}
public synchronized void receiveAuthentication(String userInput, String requestId) {
finalUserInput = userInput;
flag = false;
notify();
}
}
class T1 implements Runnable {
Authenticate m;
private final String deviceId;
private final String requestId;
String result;
public T1(Authenticate m1, String deviceId, String requestId)
{
this.m = m1;
this.deviceId = deviceId;
this.requestId = requestId;
Thread t1 = new Thread(this, "sendAuthentication");
t1.start();
// Wait for thread to finish before sending response
try
{
t1.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public void run()
{
result = m.sendAuthentication(deviceId, requestId);
}
public String getResult(){
return result;
}
}
class T2 implements Runnable {
Authenticate m;
private final String requestId;
private final String userInput;
public T2(Authenticate m2, String requestId, String userInput) {
this.m = m2;
this.requestId = requestId;
this.userInput = userInput;
Thread t2 = new Thread(this, "receiveAuthentication");
t2.start();
}
public void run() {
m.receiveAuthentication(userInput, requestId);
}
}
public class AuthenticationHandler {
final static Authenticate m = new Authenticate();
public static String sendRequest(String deviceId, String requestId)
{
T1 runnable = new T1(m, deviceId, requestId);
String result = runnable.getResult();
return result;
}
public static void receiveResponse(String requestId, String userInput)
{
new T2(m, requestId, userInput);
}
}

Related

FileZilla won't react on commands from my java FTP server

I write my own Java FTP server. Until recently I used PUttY to debug my control telnet connection and everything seemed fine - I had successful two-way communication. Now I try to debug my server with FileZilla, but it does not seem to read my text, nor to send some to server, so it just hangs and wait for something.
Control connection class
public class ControlConnection extends Thread {
private enum OperationMode {
ACTIVE, PASSIVE
}
private final Map<String, Supplier<String>> COMMANDS;
private String[] userTokens;
private User user;
private String userLogin;
private boolean authenticated;
private boolean dataConnected;
private boolean userExists;
private final Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private DataConnection ftpSession;
private OperationMode operationMode;
private String errorMessage;
public ControlConnection(Socket socket) {
super(ControlConnection.class.toString());
this.socket = socket;
// constants initialization
authenticated = false;
dataConnected = false;
// commands initialization
COMMANDS = new HashMap<>();
// commands init
}
#Override
public void run() {
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
sendGreetings();
IOProcessing.writeBytes(outputStream, pasvCommand());;
boolean running = true;
while (running) {
sendGreetings();
String input = IOProcessing.readBytes(inputStream);
if (!(input.equals("")))
System.out.println(input);
if (!checkInput(input))
continue;
userTokens = input.split(" ");
String command = userTokens[0].toUpperCase();
String answer = COMMANDS.get(command).get();
outputStream.writeBytes(answer);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
private boolean commonCheck() {
// some checks
return true;
}
private String getErrorMessage() {
return errorMessage;
}
public void sendGreetings() {
String greetings = String.format("220 Control connection established: %s", getConnectionInfo());
IOProcessing.writeBytes(outputStream, greetings);
}
public String getConnectionInfo() {
String info = String.format("%s: %d %s",
socket.getInetAddress().toString(), socket.getPort(), user != null ? user.getUsername(): "");
return info;
}
// input/output proccessing functions
public boolean checkInput(String input) {
// checks
return true;
}
// commands functions
private String pasvCommand() {
if (operationMode == OperationMode.PASSIVE) {
errorMessage = "Already in passive mode.%n";
return errorMessage;
}
String answer;
new ListenToSocket().start();
answer = String.format("227 Entering Passive Mode (%s, %d)",
"127.0.0.1", DataConnection.PORT);
operationMode = OperationMode.PASSIVE;
return answer;
}
private class ListenToSocket extends Thread {
public ListenToSocket() {
}
#Override
public void run() {
try {
ServerSocket ftpSocket =
new ServerSocket(DataConnection.PORT);
ftpSession =
DataConnection.getDataConnection(ftpSocket.accept());
if (ftpSession != null) {
ftpSession.start();
dataConnected = true;
String greetings = "Data connection established: " + ftpSession.getConnectionInfo();
IOProcessing.writeBytes(outputStream, greetings);
} else {
dataConnected = false;
}
} catch (IOException e) {
System.out.print(e);
}
}
}
also, server does not get user credentials, entered in FileZilla - input from server is always empty
IOProcessing class
public class IOProcessing {
private static final Charset UTF8_CHARSET;
static {
UTF8_CHARSET = Charset.forName("UTF-8");
}
public static String readBytes(DataInputStream inputStream) {
String result = "";
try {
int len = inputStream.available();
if (len == 0) {
return result;
}
byte[] byteInput = new byte[len];
inputStream.readFully(byteInput, 0, len);
result = new String(byteInput, "UTF-8").trim();
} catch (IOException e) {
System.err.println(e);
}
return result;
}
output FileZlla log
Status: Resolving address of localhost
Status: Connecting to [::1]:21...
Status: Connection established, waiting for welcome message.
You didn't show us the writeBytes. So I can only guess that you are not sending \r\n after the messages sent to the client. Particularly after the welcome message. So FileZilla keeps waiting forever for it, as any FTP client would do.

Reader-Writer and priority

I'm working on a system Reader-Writer with the Java threads, and it must be prioritized : the reader has the priority over the writer.
I wrote a source-code, which compiles and can be executed without any problem. But I would want to be really sure it's correct.
Can you tell me if you see some errors ?
Well, first I have to explain you the aim of my little program. At regular intervals, a message is displayed to the user. The latter can modify it, and change its display delay (the "interval of time"). A message is identified by an ID.
So if the user type : 0 \n Hello \n 2, it means the message n°0 is now "Hello" and will be displayed every 2 seconds.
Each message is taken care by a thread. I have to use semaphores.
SOURCE-CODES.
The reader :
public class Lecteur extends Thread {
private Message<String> message;
public Lecteur(Message<String> message) {
this.message = message;
}
public void run() {
try {
while(true) {
System.out.println(message.getContent());
int time = message.getRefresh_time()*1000;
Thread.sleep(time);
}
} catch(InterruptedException e) {
System.out.println(e);
}
}
}
The writer :
import java.util.HashMap;
import java.util.Scanner;
public class GestionnaireSaisie extends Thread {
private HashMap<Integer, Message<String>> messages;
public GestionnaireSaisie(HashMap<Integer, Message<String>> messages) {
this.messages = messages;
}
public void run() {
Scanner scanner = new Scanner(System.in);
int id;
String content;
int time_refresh;
while (true) {
id = scanner.nextInt();
content = scanner.next();
time_refresh = scanner.nextInt();
Message<String> found_msg = messages.get(id);
found_msg.setContent(content);
found_msg.setRefreshTime(time_refresh);
}
}
}
And the most interesting class, the shared object which contains shared data :
import java.util.concurrent.Semaphore;
public class Message<T> {
private static int maxid;
private int id;
private T content;
private int refresh_time;
public Semaphore mutex_content, mutex_refresh_time, semNbl;
public static int nbL = 0;
public int getId() {
return id;
}
public Message(T content, int refresh_time, Semaphore mutex_content, Semaphore mutex_refresh_time, Semaphore semNbl) {
id = maxid;
Message.maxid++;
this.content = content;
this.refresh_time = refresh_time;
this.mutex_content = mutex_content;
this.mutex_refresh_time = mutex_refresh_time;
this.semNbl = semNbl;
}
// <!-- CONTENT
public void setContent(T content) {
try {
mutex_content.acquire();
this.content = content;
mutex_content.release();
} catch(InterruptedException e) {
System.out.println(e);
}
}
public T getContent() {
T ret = null;
try {
semNbl.acquire();
Message.nbL++;
if(Message.nbL == 1) {
mutex_content.acquire();
}
semNbl.release();
ret = content;
semNbl.acquire();
Message.nbL--;
if(Message.nbL == 0) {
mutex_content.release();
}
semNbl.release();
} catch(InterruptedException e) {
System.out.println(e);
}
return ret;
}
// CONTENT -->
// <!-- REFRESH TIME
public void setRefreshTime(int refresh_time) {
try {
mutex_refresh_time.acquire();
this.refresh_time = refresh_time;
mutex_refresh_time.release();
} catch(InterruptedException e) {
System.out.println(e);
}
}
public int getRefresh_time() {
int ret = 0;
try {
semNbl.acquire();
Message.nbL++;
if(Message.nbL == 1) {
mutex_refresh_time.acquire();
}
semNbl.release();
ret = refresh_time;
semNbl.acquire();
Message.nbL--;
if(Message.nbL == 0) {
mutex_refresh_time.release();
}
semNbl.release();
} catch(InterruptedException e) {
System.out.println(e);
}
return ret;
}
// REFRESH TIME -->
}
Here some code to test it :
Semaphore mutex_content = new Semaphore(1);
Semaphore mutex_refresh_time = new Semaphore(1);
Semaphore semNbl = new Semaphore(1);
Message<String> message1 = new Message<String>("Bonjour le monde !", 5, mutex_content, mutex_refresh_time, semNbl);
new Lecteur(message1).start();
HashMap<Integer, Message<String>> messages = new HashMap<Integer, Message<String>>();
messages.put(message1.getId(), message1);
GestionnaireSaisie gs = new GestionnaireSaisie(messages);
gs.start();

playframework-2.3 Akka-Async interaction porting?

I have some old playframework 2.2 java webservice that interacts with akka, and now I should port them to playframework 2.3.
However, async has been deprecated and even after reading the doc about the async porting (http://www.playframework.com/documentation/2.3.x/JavaAsync) I wasn't able to understand how to apply it to my case (code below):
I must make the await for a timeout/akka server reply before starting the construction of my reply (ok()), otherwise I will block the thread.
I should make the actorselection async too.
I should make the akka server reply parsing/reply construction async too
I looked around and I wasn't able to find an example of such interactions, even in typesafe templates.
How could I do that?
/* playframework 2.2 code */
public class Resolve extends Controller {
private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
#CorsRest
#VerboseRest
#RequireAuthentication
#BodyParser.Of(BodyParser.Json.class)
public static Result getJsonTree() {
JsonNode json = request().body().asJson();
ProtoBufMessages.ResolveRequest msg;
ResolveRequestInput input;
try {
input = new ResolveRequestInput(json);
} catch (rest.exceptions.MalformedInputException mie) {
return badRequest(mie.getMessage());
}
msg = ((ProtoBufMessages.ResolveRequest)input.getMessage());
ActorSelection resolver = Akka.system().actorSelection(RESOLVER_ACTOR);
Timeout tim = new Timeout(Duration.create(4, "seconds"));
Future<Object> fut = Patterns.ask(resolver, input.getMessage(), tim);
return async (
F.Promise.wrap(fut).map(
new F.Function<Object, Result>() {
public Result apply(Object response) {
ProtoBufMessages.ResolveReply rsp = ((ProtoBufMessages.ResolveReply)response);
ResolveOutput output = new ResolveOutput(rsp);
return ok(output.getJsonReply());
}
}
)
);
}
}
I came out with the code below
public class Resolve extends Controller {
private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
private final static BrainProtoMessages.ResolveReply request_error = BrainProtoMessages.ResolveReply.newBuilder()
.setReturnCode(BResults.REQUEST_FAILED)
.build();
#CorsRest
#VerboseRest
#RequireAuthentication
#BodyParser.Of(BodyParser.Json.class)
public static Result resolve_map() {
final ResolveRequestInput input;
final F.Promise<ActorSelection> selected_target;
final F.Promise<Future<Object>> backend_request;
final F.Promise<BrainProtoMessages.ResolveReply> backend_reply;
final F.Promise<ObjectNode> decode_json;
final F.Promise<Result> ok_result;
final JsonNode json = request().body().asJson();
try {
input = new ResolveRequestInput(json);
} catch (rest.exceptions.MalformedInputException mie) {
return badRequest(mie.getMessage());
}
selected_target = F.Promise.promise(
new F.Function0<ActorSelection>() {
#Override
public ActorSelection apply() throws Throwable {
return Akka.system().actorSelection(RESOLVER_ACTOR);
}
}
);
backend_request =
selected_target.map(
new F.Function<ActorSelection, Future<Object>>() {
#Override
public Future<Object> apply(ActorSelection actorSelection) throws Throwable {
return Patterns.ask(actorSelection, input.getMessage(),new Timeout(Duration.create(4, "seconds")));
}
}
);
backend_reply = backend_request.map(
new F.Function<Future<Object>, BrainProtoMessages.ResolveReply>() {
#Override
public BrainProtoMessages.ResolveReply apply(Future<Object> akka_reply) throws Throwable {
try {
return (BrainProtoMessages.ResolveReply) Await.result(akka_reply, Duration.create(4, "seconds"));
}catch(Exception error)
{
return request_error;
}
}
}
);
decode_json = backend_reply.map(
new F.Function<BrainProtoMessages.ResolveReply, ObjectNode>() {
#Override
public ObjectNode apply(BrainProtoMessages.ResolveReply response) throws Throwable {
return new ResolveOutput(response).getJsonReply();
}
}
);
ok_result = decode_json.map(
new F.Function<ObjectNode, Result>() {
#Override
public Result apply(ObjectNode reply) {
return ok(reply);
}
}
);
try {
return ok_result.get(8000);
}catch(Exception error)
{
return internalServerError();
}
}
}

Java BufferedReader receives null string

My program is laid out so that the main app can send commands to any node connected to it. When a node receives a request, it returns a response and continues to wait for more requests.
When the app is run the node successfully replies to one request, and when a second request is sent the node sees it as a null or does not see it at all. Why does this keep happening?
P.S. I want the connection to the node to stay open, so that it can receive more requests.
Request sending code:
public java.lang.String getTime(server.Node node){
protocol.Message ms = new protocol.Message("<time>","");
node.sendRequestToClient(ms);
node.dos.flush();
java.lang.System.out.println("Sent time request to " + node.ip);
java.lang.String time = null;
try {
time = node.dis.readLine();
} catch (java.io.IOException ex) {
System.out.println("Could not read response.");
}
protocol.Message response = protocol.Message.parseDataToMessage(time);
java.lang.String systime = response.getActionData();
return systime;
}
Response sending code:
public class Client {
public Client(NetworkConnection connection){
this.connectionToServer = connection;
try{
connectionToServer.connect();
responseOutStream = connectionToServer.getPrintWriter();
requestInStream = connectionToServer.getBufferedReader();
}catch(IOException ex){
System.out.println("Could not connect to server." + ex.getMessage() + ex.toString());
}
}
public void beginRequestListener(){
String request;
try {
while((request = requestInStream.readLine())!=""){
System.out.println("Recieved request: " + request + request.length());
Message response = Message.parseDataToMessage(request);
sendResponseToServer(response);
}
} catch (java.io.IOException ex) {
System.out.println("Could not read request stream.");
} catch(NullPointerException e){
e.printStackTrace();
e.getClass();
}
}
public void sendResponseToServer(Message ms){
protocol.Message response = MessageParser.compileResponse(ms);
java.lang.System.out.println("Response to send: "+response);
response.send(responseOutStream);
}
public BufferedReader requestInStream;
public PrintWriter responseOutStream;
public NetworkConnection connectionToServer;
}
MessageParser class:
public class MessageParser {
static public Message compileResponse(Message ms){
Message response = null;
switch(ms.getAction()){
case "<time>":
response = new Message("<time>", String.valueOf(System.currentTimeMillis()));
break;
case "<date>":
SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
Date date = new Date();
sd.setTimeZone(TimeZone.getTimeZone("IST"));
response = new Message("<date>", date.toString());
break;
default:
break;
}
return response;
}
}
The stack trace and output:
Recieved request: <action><time><action><actionData><actionData>
Response to send: <action><time><action><actionData>1370380854566<actionData>
Recieved request:
java.lang.NullPointerException
at protocol.MessageParser.compileResponse(MessageParser.java:23)
at client.Client.sendResponseToServer(Client.java:67)
at client.Client.beginRequestListener(Client.java:52)
at client.ClientInterface.main(ClientInterface.java:107)
Message class:
public class Message {
public Message(String data){
}
public Message(String action, String actionData){
this.action = action;
this.actionData = actionData;
}
public void send(PrintWriter connection){
try{
connection.println(this.toString());
connection.flush();
//System.out.println(this.toString());
}catch(Exception ex){
System.out.println("Could not send Message.");
}
}
#java.lang.Override
public String toString(){
return
action_marker + action + action_marker +
actionData_marker + actionData + actionData_marker +
eof_marker;
}
public static Message parseDataToMessage(String data){
Message ms = null;
if(data.isEmpty() == false){
int begin_action_marker = data.indexOf("<action>")+8;
int end_action_marker = data.lastIndexOf("<action>");
String action = data.substring(begin_action_marker, end_action_marker);
int begin_actionData_marker = data.indexOf("<actionData>")+12;
int end_actionData_marker = data.lastIndexOf("<actionData>");
String actionData = data.substring(begin_actionData_marker, end_actionData_marker);
ms = new Message(action, actionData);
}
return ms;
}
public void setAction(String action){
this.action = action;
}
public String getActionData(){
return actionData;
}
public String getAction(){
return action;
}
public void setActionData(String action){
this.actionData = action;
}
public String eof_marker = "\r\n";
public String action;
public String action_marker = "<action>";
public String actionData;
public String actionData_marker = "<actionData>";
}
My guess:
you receive an empty request in (request = requestInStream.readLine())
this goes to Message.parseDataToMessage(request); which returns null for empty requests
that generates a NullPointerException in compileResponse
The (likely) solution: change this
while((request = requestInStream.readLine())!=""){
into this:
while(!(request = requestInStream.readLine()).isEmpty())
Why your code does not work: How do I compare strings in Java?
while((request = requestInStream.readLine())!=""){
What's this test for? Are you expecting empty requests? You shouldn't be. If you get one it's a bug at the sender.
However you must test the result of readLine() for null before doing anything else with it. The line should read:
while((request = requestInStream.readLine())!= null){

Java: Serializing beginner problem :-(

I want to save and store simple mail objects via serializing, but I get always an error and I can't find where it is.
package sotring;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import com.sun.org.apache.bcel.internal.generic.INEG;
public class storeing {
public static void storeMail(Message[] mail){
try {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("mail.ser"));
out.writeObject(mail);
out.flush();
out.close();
} catch (IOException e) {
}
}
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
for (int i=0; i< array.length;i++)
System.out.println("EMail von:"+ array[i].getSender() + " an " + array[i].getReceiver()+ " Emailbetreff: "+ array[i].getBetreff() + " Inhalt: " + array[i].getContent());
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
return null;
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user1 = new User("User1", "geheim");
User user2 = new User("User2", "geheim");
Message email1 = new Message(user1.getName(), user2.getName(), "Test", "Fooobaaaar");
Message email2 = new Message(user1.getName(), user2.getName(), "Test2", "Woohoo");
Message email3 = new Message(user1.getName(), user2.getName(), "Test3", "Okay =) ");
Message [] mails = {email1, email2, email3};
storeMail(mails);
Message[] restored = getStoredMails();;
}
}
Here are the user and message class
public class Message implements Serializable{
static final long serialVersionUID = -1L;
private String receiver; //Empfänger
private String sender; //Absender
private String Betreff;
private String content;
private String timestamp;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Message (String receiver, String sender, String Betreff, String content) {
this.Betreff= Betreff;
this.receiver = receiver;
this.sender = sender;
this.content = content;
this.timestamp = getDateTime();
}
Message() { // Just for loaded msg
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getBetreff() {
return Betreff;
}
public void setBetreff(String betreff) {
Betreff = betreff;
}
public String getContent() {
return content;
}
public String getTime() {
return timestamp;
}
public void setContent(String content) {
this.content = content;
}
}
public class User implements Serializable{
static final long serialVersionUID = -1L;
private String username; //unique Username
private String ipadress; //changes everytime
private String password; //Password
private int unreadMsg; //Unread Messages
private static int usercount;
private boolean online;
public String getName(){
return username;
}
public boolean Status() {
return online;
}
public void setOnline() {
this.online = true;
}
public void setOffline() {
this.online = false;
}
User(String username,String password){
if (true){
this.username = username;
this.password = password;
usercount++;
} else System.out.print("Username not availiable");
}
public void changePassword(String newpassword){
password = newpassword;
}
public void setIP(String newip){
ipadress = newip;
}
public String getIP(){
if (ipadress.length() >= 7){
return ipadress;
} else return "ip address not set.";
}
public int getUnreadMsg() {
return unreadMsg;
}
}
Here is the exception:
exception in thread "main" java.lang.Error: Unresolved compilation problem:
This method must return a result of type Message[]
at sotring.storeing.getStoredMails(storeing.java:22)
at sotring.storeing.main(storeing.java:57)
THANK YOU FOR YOUR HELP!!!!!!!!!!!
The catch clauses need to return something.
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null; //fix
}
If an exception occurs, you never get to the return statement in getStoredMails. You need to either throw the exception you catch (possibly wrapping it in another more descriptive exception) or just return null at the end of the method. It really depends on what you want to do if there's an error.
Oh, and your in.close() should be in a finally block. Otherwise, it is possible that you could read the data fine but then throw it away if you can't close the stream.
On a different note, have you considered a third-party serializer library?
I'm using Simple right now for a project, and it seems to do stuff just fine with very little effort.
in the exception handling blocks of the getStoredMails method you do not return anything.
Suggested modification:
public static Message[] getStoredMails(){
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("mail.ser"));
Message[] array = (Message[]) in.readObject() ;
System.out.println("Size: "+array.length); //return array;
in.close();
return array;
}
catch(IOException ex)
{
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
return null;
}
I modified the source. I added "return null" in exception and the for loop the output in the function. And the function gives me the right output but then throws it the exception.

Categories

Resources