Using socket to connet gmail and send gmail, but not work - java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SMTPDemo {
public static void main(String args[]) throws IOException,
UnknownHostException {
String msgFile = "file.txt";
String from = "java2s#java2s.com";
String to = "yourEmail#yourServer.com";
String mailHost = "yourHost";
SMTP mail = new SMTP(mailHost);
if (mail != null) {
if (mail.send(new FileReader(msgFile), from, to)) {
System.out.println("Mail sent.");
} else {
System.out.println("Connect to SMTP server failed!");
}
}
System.out.println("Done.");
}
static class SMTP {
private final static int SMTP_PORT = 25;
InetAddress mailHost;
InetAddress localhost;
BufferedReader in;
PrintWriter out;
public SMTP(String host) throws UnknownHostException {
mailHost = InetAddress.getByName(host);
localhost = InetAddress.getLocalHost();
System.out.println("mailhost = " + mailHost);
System.out.println("localhost= " + localhost);
System.out.println("SMTP constructor done\n");
}
public boolean send(FileReader msgFileReader, String from, String to)
throws IOException {
Socket smtpPipe;
InputStream inn;
OutputStream outt;
BufferedReader msg;
msg = new BufferedReader(msgFileReader);
smtpPipe = new Socket(mailHost, SMTP_PORT);
if (smtpPipe == null) {
return false;
}
inn = smtpPipe.getInputStream();
outt = smtpPipe.getOutputStream();
in = new BufferedReader(new InputStreamReader(inn));
out = new PrintWriter(new OutputStreamWriter(outt), true);
if (inn == null || outt == null) {
System.out.println("Failed to open streams to socket.");
return false;
}
String initialID = in.readLine();
System.out.println(initialID);
System.out.println("HELO " + localhost.getHostName());
out.println("HELO " + localhost.getHostName());
String welcome = in.readLine();
System.out.println(welcome);
System.out.println("MAIL From:<" + from + ">");
out.println("MAIL From:<" + from + ">");
String senderOK = in.readLine();
System.out.println(senderOK);
System.out.println("RCPT TO:<" + to + ">");
out.println("RCPT TO:<" + to + ">");
String recipientOK = in.readLine();
System.out.println(recipientOK);
System.out.println("DATA");
out.println("DATA");
String line;
while ((line = msg.readLine()) != null) {
out.println(line);
}
System.out.println(".");
out.println(".");
String acceptedOK = in.readLine();
System.out.println(acceptedOK);
System.out.println("QUIT");
out.println("QUIT");
return true;
}
}
}
I want learn about how to make smtp server to using socket.
I find this example code on this site.
When I write this code in Eclipse and compile but socekt smtpPipe is error.
Eclipse error message:
Resource leak : 'smtpPipe is never closed'.
I don't know how to solve this problem.

Eclipse error message : Resource leak : 'smtpPipe is never closed'
It says you are not closing the resource smtpPipe. The recommended practice is to close the resource when it is no longer needed. You can achieve this by calling smtpPipe.close() method.
One way of doing is to wrap your code around try and finally block. Read more about finally block here.
Example:
try {
....
smtpPipe = new Socket(mailHost, SMTP_PORT);
....
} finally {
if (smtpPipe != null)
smtpPipe.close();
}
Also, use the similar approach for other resources like InputStream and OutputStream

Related

Trouble writing to OutputStream socket

I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.

Simple Mail Client in Java - getting 501 5.5.4 Invalid Domain Name

I'm writing a simple mail client that needs to do the following:
Establish a TCP connection with a mail server.
Send/receive messages to/from the mail server.
Close the connection with the mail server.
So far, my client will setup a connection just fine, but when it tries to send "HELO" + my InetAddress, the host says the domain name is invalid.
How do I resolve this so that I can send email via my mail client?
Here is my code:
package main;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MailClient {
private static int port;
private static String mailServer;
private Socket sock;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private BufferedReader br;
//private OutputStreamWriter osw;
private PrintWriter pw;
public MailClient(String mailServer, int port) {
this.mailServer = mailServer;
this.port = port;
}
// Establish TCP connection with mail server
public void setUpConnection() {
System.out.println("Setting up connection to server...\n");
try {
sock = new Socket(mailServer, port);
inputStream = new DataInputStream(sock.getInputStream());
outputStream = new DataOutputStream(sock.getOutputStream());
br = new BufferedReader(new InputStreamReader(inputStream));
pw = new PrintWriter(outputStream);
//osw = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
if(readResponse() == 220) {
System.out.println("Connection established!\n");
}
} catch (UnknownHostException e) {
System.err.println("Host name" + mailServer + " isn't recognized\n");
} catch (IOException e) {
System.err.println("I/O for host " + mailServer + " failed.\n");
}
}
// Dialogue with mail server using SMTP
public void sendMessage(String from, String to, String subject, String message) {
System.out.println("Sending message to server...\n");
try {
String response;
writeMsg("HELO " + InetAddress.getLocalHost().getHostName() + "\n");
readResponse();
writeMsg("MAIL FROM: " + from + "\n");
readResponse();
writeMsg("RCPT TO: " + to + "\n");
readResponse();
writeMsg("DATA\n");
readResponse();
writeMsg("From: " + from + "\n");
writeMsg("To: " + to + "\n");
writeMsg("Date: " + "\n");
writeMsg("Subject: " + subject + "\n");
writeMsg(message + "\n");
writeMsg("\n.\n");
readResponse();
writeMsg("QUIT");
readResponse();
System.out.println("Message sent!");
String responseFromServer;
while((responseFromServer = br.readLine()) != null) {
System.out.println("Server response: " + responseFromServer);
if(responseFromServer.indexOf("Ok") != -1) {
System.out.println("Ok recieved from mail server!");
break;
}
}
closeConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
// Close TCP connection
private void closeConnection() {
System.out.println("Closing connection to server...");
try {
br.close();
pw.close();
inputStream.close();
outputStream.close();
sock.close();
System.out.println("Connection to mail server closed.");
}catch(IOException e) {
System.err.println(e);
}
}
private int readResponse() throws IOException {
String line = br.readLine();
System.out.println("Server Response:" + line + "\n");
line = line.substring(0, line.indexOf(" "));
return Integer.parseInt(line);
}
private void writeMsg(String message) {
pw.println(message);
pw.flush();
System.out.println("Message to server: " + message);
}
public static void main(String[] args) {
String emailAddress = "test#domain.edu";
String subject = "test";
String message = "hello world";
String test= "mailserver.edu";
MailClient mc = new MailClient(test, 587);
mc.setUpConnection();
mc.sendMessage("example#yahoo.com", emailAddress, subject, message);
}
}
The verbatim error I'm getting: 501 5.5.4 Invalid domain name

transformer to socket not working

Its driving me nuts trying days to grind this problem.
I am writing a java server to work with an android application. They communicate text string and xml.
Currently simple socket communication seems fine, however it breaks down when I tried to use transformer instead of simple println.
Server code as below
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class javamultithreadedserver implements Runnable {
Socket csocket;
static int listenport = 6021;
public static final String endOfCom = "endofcom";
String connectionname;
public javamultithreadedserver(Socket csocket, String connectionname) {
this.csocket = csocket;
this.connectionname = connectionname;
}
public static void main(String[] args) throws Exception {
int listentoport = 0;
//System.out.println(args.length);
if (args.length == 1){
listentoport = Integer.parseInt(args[0]);
} else{
listentoport = listenport;
}
ServerSocket ssock = new ServerSocket(listentoport);
System.out.println("Listening at port " + listentoport);
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected. from: " + sock.getInetAddress().getHostAddress() + " " + sock.getInetAddress().getHostName() + " port: " + sock.getPort() + " " + sock.getInetAddress().getCanonicalHostName());
new Thread(new javamultithreadedserver(sock, sock.getInetAddress().getHostAddress() + " " + sock.getInetAddress().getHostName() + " " + sock.getInetAddress().getCanonicalHostName())).start();
}
}
#Override
public void run() {
try {
PrintWriter out = new PrintWriter(csocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
PrintStream pstream = new PrintStream (csocket.getOutputStream(), true);
String inputLine, outputLine;
System.out.println(connectionname + ": listening for query information.");
while ((inputLine = in.readLine()) != null) {
System.out.println(connectionname + ": " + inputLine);
//out.write("received something");
DBQuery q = new DBQuery(inputLine + DBQuery.regexsplit + "connectionname" + DBQuery.regexsplit + connectionname);
DOMSource dmsource = q.returns();
***//StreamResult consoleResult = new StreamResult(System.out); //debug***
StreamResult consoleResult = new StreamResult(pstream);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Thread.sleep(100);
***transformer.transform(dmsource, consoleResult);***
//out.println("println this is a testprogram"); // client receive ok
pstream.flush();
System.out.println(connectionname + ": reply sent.");
if (inputLine == endOfCom){
System.out.println(connectionname + ": is satisfied and terminated communication.");
break;
}
}
pstream.close();
csocket.close();
}catch (IOException e) {
System.out.println(e);
}catch (Exception e) {
System.out.println(e);
}
}
}
And the android client code as below:
public void run() {
if (barcode.length() > 0) {
Socket socket = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
socket.setSoTimeout(10000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write(barcode + ENDL);
if(out.checkError()){
showToUI("PrintWriter had error");
} else {
showToUI("Query sent");
}
int i = 0;
while (true) {
try{
if (**(serverResponse = in.readLine()) != null**) {
if(serverResponse == endOfCom){
Log.i("communicated all data", "bye");
out.write(endOfCom + ENDL);
break;
} else{
}
Log.i("server says", serverResponse);
}
//Log.i("server says", (serverResponse == null? "null" :serverResponse ));
}catch(SocketTimeoutException e){
showToUI(barcode + ": Server did not respond in time");
if (i++ > 2) {
break;
}
}
}
} catch (final UnknownHostException e1) {
showToUI(e1.toString());
} catch (final IOException e1) {
showToUI(e1.toString());
} finally{
try {
socket.close();
} catch (IOException e) {
showToUI(e.toString());
}
}
}else{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please enter something in barcode", Toast.LENGTH_SHORT).show();
}
});
}
}
I have tested that the xml result returned was ok, if the Stream Result was set to System.out instead of the PrintStream pstream, everything prints perfectly to the console.
However with or without pstream.flush(), client received no response at (serverResponse = in.readLine()) != null.
Also the PrintWriter out which was based on the same Socket socket of pstream successfully gave feedback to the client. When out.println("println this is a testprogram"); was called, the client received log at the Log.i("server says", serverResponse); line OK.
One thing to note is that the reply is usually quite long, can be up to 65536 characters or even more, I do not know if that has any implication, I have tried to create a Buffered reader on the android app larger than the replying xml, it still did not work. The machines are communicating on local network, java server program is running on a different machine from the android emulator.
Any help is appreciated, this had been going on for days and nowhere.
readLine() won't return null until the peer closes the connection. And when it does return null, you need to break out of the loop. And don't compare string s with ==.

Bad Requests and Timeouts

I want to access an arbitrary webpage using sockets (as a learning mechanism for myself). The code below does not work, what am I doing wrong?
import java.net.*;
import java.io.*;
public class Example
{
public static void main(String args[]) throws Exception
{
Socket socket =
new Socket("www.google.com", 80);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println("GET / HTTP/1.1 \\r\\n Host: www.google.com \\r\\n\\r\\n");
System.out.println("echo: " + reader.readLine());
}
}
}
After trying for a couple hours I was unable to figure out what exactly I was doing wrong. All I want is Google's or some other websites homepage. Can anyone help me?
You might try something like the following (using sockets)
package com.example.webpagesocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class GetWebPageUsingSockets {
public static void main(String[] args) {
String urlString;
urlString = "www.google.com";
accessWeb(urlString);
}
private static void accessWeb(String urlString) {
String host;
String page;
int slashLoc;
// Set up encoding and decoding
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
if ((slashLoc = urlString.indexOf('/')) < 0) {
host = urlString;
page = "";
} else {
host = urlString.substring(0, slashLoc);
page = urlString.substring(slashLoc);
}
System.out.println("Accessing web page demonstration");
System.out.println("Host: '" + host + "' Page: '" + page + "'");
SocketChannel channel = null;
try {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
CharBuffer charBuffer = CharBuffer.allocate(1024);
InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
channel = SocketChannel.open();
channel.connect(socketAddress);
String request = "GET " + page + " \r\n\r\n";
channel.write(encoder.encode(CharBuffer.wrap(request)));
while ((channel.read(buffer)) != -1) {
buffer.flip();
decoder.decode(buffer, charBuffer, false);
charBuffer.flip();
System.out.println(charBuffer);
buffer.clear();
charBuffer.clear();
}
} catch (UnknownHostException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
}
}
}
System.out.println("\nDone.");
}
}
Edit : didn't notice the \ at first reading ...
It looks like you are continuously sending "GET / HTTP/1.1 \\r\\n Host: www.google.com \\r\\n\\r\\n" to the host (at each read). You'd better keeping it out of the loop and sent true carriage return + line feed and not printable chars \ r \ n :
out.println("GET / HTTP/1.1 \r\nHost: www.google.com\r\n\r\n");
String userInput;
while ((userInput = stdIn.readLine()) != null) {
You only start reading after sending your GET, but the socket will buffer data.

Tricky NullPointerException while sending a file to a client

I am working on a simple server in Java that should have a capability of transferring a file across computers. I am getting a NullPointerException on line 77 of Protocol.class. Here is the stack:
java.lang.NullPointerException
at Protocol.processInput(Protocol.java:77)
at Server.main(Server.java:41)
Why does this happen? There is no null references on line 77!
Client.java:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
public class Client {
private static boolean filein = false;
private static ArrayList<String> fln = new ArrayList<>();
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java Client <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket kkSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(kkSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(kkSocket.getInputStream()));
) {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser = null;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("#file")) { filein = true;
fromUser = "";}
else if(fromServer.equals("#end#")) {
filein = false;
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String fname = chooser.getSelectedFile().getAbsolutePath();
File f = new File(fname);
f.createNewFile();
PrintWriter p = new PrintWriter(f);
for(int i = 0; i < fln.size(); i++) {
p.println(fln.get(i));
}
p.close();
JOptionPane.showMessageDialog(null, "File saved!");
}
}
else if (filein == true) {
fln.add(fromServer);
System.out.println(fln.get(fln.size() - 1));
}
if (fromServer.equals("Bye."))
break;
if (!filein) fromUser = stdIn.readLine();
else if (filein) fromUser = "#contintueFileRun";
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
}
}
}
Server.java:
import java.io.*;
import java.net.*;
import static java.lang.System.out;
/**
* Title: FTP Server
* #author Galen Nare
* #version 1.0
*/
public class Server {
public static void main(String[] args) throws IOException {
out.println("Starting server!");
if (args.length != 1) {
System.err.println("Usage: java Server <port number>");
System.exit(1);
}
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
// Initiate conversation with client
Protocol kkp = new Protocol();
outputLine = kkp.processInput("");
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = kkp.processInput(inputLine);
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And finally, Protocol.java:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Protocol {
enum ServerState {
STARTING,
WAITING
}
ArrayList<String> lns;
boolean fileout = false;
int i = 0;
private ServerState state = ServerState.STARTING;
public String processInput(String theInput) throws Exception {
String theOutput = "";
if (state == ServerState.STARTING) {
theOutput = "Hello, Client!";
state = ServerState.WAITING;
}
if (!theInput.equals("")) {
if(theInput.length() > 10 && theInput.startsWith("e")) {
if (theInput.substring(0,11).equalsIgnoreCase("executecmd ")) {
theOutput = theInput.substring(11);
System.out.println(theOutput);
try {
#SuppressWarnings("unused")
Process child = Runtime.getRuntime().exec(theInput.substring(11));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
theOutput = "Executed " + theInput.substring(11) + ".";
}
} else if (theInput.equalsIgnoreCase("stop")) {
theOutput = "Stopping Server!";
System.exit(0);
} else if (theInput.equalsIgnoreCase("executecmd")) {
theOutput = "Usage: executecmd <command [-options]>";
} else if (theInput.equalsIgnoreCase("getfile")) {
theOutput = "Usage: getfile <file>";
} else if(theInput.length() > 7 && theInput.startsWith("g")) {
System.out.println("in");
if (theInput.substring(0,8).equalsIgnoreCase("getfile ")) {
theOutput = theInput.substring(8);
File f = new File(theInput.substring(8));
Scanner scan = new Scanner(f);
ArrayList<String> lns = new ArrayList<>();
while(scan.hasNext()) {
lns.add(scan.nextLine());
}
for (int i=0; i < lns.size(); i++) {
System.out.println(lns.get(i));
}
scan.close();
lns.add("#end#");
theOutput = "#file";
fileout = true;
}
} else if (fileout && i < lns.size()) {
theOutput = lns.get(i);
i++;
} else if (fileout && i == lns.size()) {
i = 0;
fileout = false;
} else {
theOutput = "That is not a command!";
}
}
System.out.print(theOutput);
return theOutput;
}
}
Thanks in advance!
You're never initializing lns in Protocol, so it's always a null reference. You may be able to get away with just changing the declaration to:
private List<String> lns = new ArrayList<String>();
(I've made it private and changed the type to List just out of habit...)
You should also consider giving it a more readable name - is it meant to represent lines? If so, call it lines!
(Next, consider why you weren't able to diagnose this yourself. Did you step through this in the debugger? Why did you think there were no null references on line 77? What diagnostic steps did you take in terms of adding extra logging etc? It's important to use errors like this as a learning experience to make future issues more tractable.)

Categories

Resources