File Server Problem In this problem we will take our solution to JH2 called File
ID: 3856543 • Letter: F
Question
File Server Problem
In this problem we will take our solution to JH2 called FileOperations and we will make it work across a network. From this we will have in effect the beginnings of a minimal File Server. You can start from your solution or you can start from the published answer to JH2.
I would recommend that you use 2 work spaces and 2 instances of Eclipse to develop this .... one for the Client side and one for the FileServer side.
Note that all of our FileOperations commands were a one line command. However, the output for a given command could be many lines. To make this work, we need invent the following protocol:
Summary of the above Server changes:
My Soultion to JH2 File Operations
import java.io.*;
import java.util.*;
public class FileOperations {
StringTokenizer parseCommand;
String fileForAction = "";
File path;
public void delete() {
boolean returnCode = false;
if (path.exists()) {
System.out.println("Deleting: " + path.getAbsolutePath());
returnCode = path.delete();
} else {
System.out.println("File does not exist: " + path);
}
if (returnCode == true) {
System.out.println("Successful Deletion");
} else {
System.out.println("Failed to Delete.");
}
printSeperator();
// code for handling the delete command
// Make sure you check the return code from the
// File delete method to print out success/failure status
}
public void rename(ArrayList<String> commandArguments) {
File newPath = new File(commandArguments.get(0));
boolean returnCode = false;
if (path.exists()) {
System.out.println("Renaming: " + path.getAbsolutePath());
returnCode = path.renameTo(newPath);
System.out.println(newPath);
} else {
System.out.println("File does not exist.");
}
if (returnCode == true) {
System.out.println("Successful Rename");
} else {
System.out.println("Failed to Rename.");
}
printSeperator();
}
public void list() {
if (path.exists()) {
if (path.isDirectory()) {
System.out.println("Listing: " + path.getAbsolutePath());
for (int i = 0; i < path.list().length; i++) {
System.out.println(path.list()[i]);
}
} else
System.out.println("Not a directory:" + path);
} else
{
System.out.println("Directory does not exist.");
}
printSeperator();
}
public void size() {
if (path.exists()) {
System.out.println("Size for: " + path.getAbsolutePath());
System.out.println("Size in bytes: " + path.length());
} else {
System.out.println("File does not exist.");
}
printSeperator();
}
public void mkdir() {
boolean returnCode = path.mkdir();
if (returnCode == true) {
System.out.println("Successful directory creation.");
} else {
System.out.println("Failed to create directory");
}
}
public void createFile(ArrayList<String> commandArguments) {
try {
PrintStream printer = new PrintStream(new FileOutputStream(path));
for (int i = 0; i < commandArguments.size(); i++) {
printer.println(commandArguments.get(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("Created file for: " + path.getAbsolutePath());
printSeperator();
}
}
public void printFile() {
Scanner fileIn = null;
try {
fileIn = new Scanner(new FileInputStream((path)));
while (fileIn.hasNextLine()) {
System.out.println(fileIn.nextLine());
}
System.out.println("Printed file for: " + path.getAbsolutePath());
} catch (FileNotFoundException e) {
System.out.println("Error. File not found." + e);
} finally {
if (fileIn != null)
fileIn.close();
printSeperator();
}
}
public void lastModified() {
if (path.exists() && path.isFile()) {
System.out.println("Last modified for: " + path.getAbsolutePath());
System.out.println(new Date(path.lastModified()));
} else {
System.out.println("File does not exist.");
}
printSeperator();
}
void printSeperator() {
System.out.println("************************");
}
void printUsage() {
// process the "?" command
String[] validCommands = {"?", "quit", "delete", "rename", "size", "lastModified", "list", "printFile", "createfile", "mkdir", "quit"};
for (int i = 0; i < validCommands.length; i++) {
System.out.println(validCommands[i]);
}
printSeperator();
}
public void processCommandLine(String line) {
try {
StringTokenizer parseCommand = new StringTokenizer(line);
String command = parseCommand.nextToken();
System.out.println("Processing: " + line);
ArrayList<String> commandArguments = new ArrayList<>();
while (parseCommand.hasMoreTokens()) {
commandArguments.add(parseCommand.nextToken());
}
if (commandArguments.size() != 0) {
fileForAction = commandArguments.get(0);
path = new File(fileForAction);
commandArguments.remove(0);
}
switch (command) {
case "?":
printUsage();
break;
case "createFile":
createFile(commandArguments);
break;
case "printFile":
printFile();
break;
case "lastModified":
lastModified();
break;
case "size":
size();
break;
case "rename":
rename(commandArguments);
break;
case "mkdir":
mkdir();
break;
case "delete":
delete();
break;
case "list":
list();
break;
case "quit":
System.out.println("Bye.");
return;
default:
System.out.println("Invalid command: " + line);
printSeperator();
break;
}
} catch (NullPointerException e) {
System.out.println("File argument is missing. Exception is: " + e);
printSeperator();
} catch (NoSuchElementException e) {
System.out.println("Command is missing. Exception is: " + e);
printSeperator();
}
}
void processCommandFile(String commandFile) {
Scanner fileIn = null;
File commandFileToRead = new File(commandFile);
String marker = "=====================================================================";
try {
fileIn = new Scanner(new FileInputStream((commandFile)));
System.out.println(marker);
System.out.println("Starting command file = " + commandFileToRead.getAbsolutePath());
System.out.println(marker);
while (fileIn.hasNextLine()) {
processCommandLine(fileIn.nextLine());
}
System.out.println(marker);
System.out.println("Ending command file = " + commandFileToRead.getAbsolutePath());
System.out.println(marker);
} catch (FileNotFoundException e) {
System.out.println("Error. File not found." + e);
} finally {
if (fileIn != null)
fileIn.close();
}
}
public static void main(String[] args) {
FileOperations fo = new FileOperations();
for (int i = 0; i < args.length; i++) {
System.out.println(" ============ Processing " + args[i] + " ======================= ");
fo.processCommandFile(args[i]);
}
System.out.println("Done with file_operations.FileOperations");
}
}
Explanation / Answer
Program has two packages
File_Client
-echoClient
-FileClient
File_Server
-ConnectListener
-EchoServer
-FileServer
-MotherServer
-----------------------------------------------------
EchoClient.java
------------------------
package file_client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoClient {
Socket socket=null;
void communicate(InputStream is, OutputStream os)
{
Scanner scanSocket = new Scanner(is);
PrintStream psSocket = new PrintStream(os, true);
Scanner keyboard = new Scanner(System.in);
System.out.println("Start entering commands for FileClient ....");
String fromKeyboard= keyboard.nextLine();
while (!fromKeyboard.equals("quit"))
{
psSocket.println(fromKeyboard); // write to socket
String sFromSocket = scanSocket.nextLine(); // read from socket
System.out.println("received from server: "+sFromSocket);
fromKeyboard = keyboard.nextLine();
}
scanSocket.close();
psSocket.close();
keyboard.close();
System.out.println("Exitting communicate");
}
public void startup(String[] args){
String hostName="localhost";
int portNum=4444;
InputStream is = null;
OutputStream os = null;
if (args.length > 0)
hostName = args[0];
if (args.length > 1)
{
// An exception can occur here if bad data is entered
portNum = Integer.parseInt(args[1]);
}
try {
socket = new Socket(hostName, portNum);
is = socket.getInputStream();
os = socket.getOutputStream();
communicate(is,os);
is.close();
os.close();
}
catch (UnknownHostException e) {
System.out.println("startup.UnknownHostException: "+e);
}
catch (IOException e) {
System.out.println("startup.IOException: "+e);
}
System.out.println("Exitting startup");
}
public static void main(String[] args) {
EchoClient echoClient= new EchoClient();
echoClient.startup(args);
System.out.println("Exitting main");
}
}
------------------------------------------------------------------------
FileClient.java
-------------------------------
package file_client;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class FileClient extends EchoClient {
public void communicate (InputStream is, OutputStream os){
Scanner scanSocket = new Scanner(is);
PrintStream psSocket = new PrintStream(os, true);
Scanner keyboard = new Scanner(System.in);
System.out.println("Start entering text to FileServer ....");
String fromKeyboard= keyboard.nextLine();
do
{
psSocket.println(fromKeyboard); // write to socket
while (scanSocket.hasNextLine())
{
String sFromSocket = scanSocket.nextLine(); // read from socket
if (sFromSocket.length() == 0)
break;
System.out.println("received from server: "+sFromSocket);
}
fromKeyboard = keyboard.nextLine();
} while (!fromKeyboard.equals("quit"));
scanSocket.close();
psSocket.close();
keyboard.close();
System.out.println("Exitting communicate");
}
public static void main(String[] args) {
FileClient fc= new FileClient();
fc.startup(args);
System.out.println("Exitting main");
}
}
------------------------------------------------------------------------
ConnectListener.java
-------------------------------
package file_server;
import java.net.Socket;
public interface ConnectListener {
public void handleConnect(Socket s);
}
------------------------------------------------------------------------
EchoServer.java
-------------------------------
package file_server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
public class EchoServer implements Runnable, Cloneable{
Socket clientSocket=null;
Thread myThread = null;
public void handleConnect(Socket s) {
clientSocket = s;
// Something very unique is happening here.
// We want each connection to run on its own object
// However we don't want to call the EchoServer constructor to get this.
// We want this class to be the base of many other protocol handler classes.
// By calling clone, we will make an instance that has the characteristics of the
// derived class instead of the EchoServer.
try {
Runnable protocol_handler = (Runnable)clone();
Thread myThread = new Thread(protocol_handler);
System.out.println("Launching a new Child Thread");
myThread.start();
}
catch (CloneNotSupportedException e) {
System.out.println("EchoServer.handleConnect Clone error: "+e);
}
}
public void run()
{
InputStream is=null;
OutputStream os=null;
try {
is = clientSocket.getInputStream();
os = clientSocket.getOutputStream();
processStream(is, os);
}
catch (IOException e) {
System.out.println("Server Exception: "+e);
}
finally
{
try
{
if (is != null) is.close();
if (os != null) os.close();
}
catch (IOException e)
{
System.out.println("run: Stupid exception that shouldn't happen");
}
}
System.out.println("Exitting Child Server Thread");
}
public void processStream(InputStream is, OutputStream os)
{
System.out.println("FileServer.processStream begins");
Scanner input = new Scanner(is);
PrintStream ps = new PrintStream(os);
while (input.hasNextLine())
{
processNextLine(input, ps);
}
input.close();
ps.close();
System.out.println("Exitting processStream");
}
public void processNextLine(Scanner input, PrintStream ps)
{
String s= input.nextLine();
ps.println(s);
System.out.println("FileServer echoed: "+s);
}
public void monitorServer()
{
MotherServer myServer = new MotherServer();
System.out.println(MotherServer.getHostInfo());
myServer.startServer(4444, this);
Scanner keyboard = new Scanner(System.in);
String s="";
while (!s.equals("quit"))
{
System.out.println("Whenever you want to stop the server, enter "quit" ");
s = keyboard.next();
}
keyboard.close();
myServer.stopServer();
}
public static void main(String[] args) {
EchoServer es = new EchoServer();
es.monitorServer();
System.out.println("Exitting FileServer");
}
}
------------------------------------------------------------------------
FileServer.java
-------------------------------
package file_server;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileServer extends EchoServer
{
StringTokenizer parseCommand;
PrintStream outputPS = null;
public void delete()
{
File f = getFile();
if (f != null)
{
outputPS.println("deleting "+ f.getAbsolutePath());
if (f.delete())
outputPS.println(" Successful delete");
else
outputPS.println(" unSuccessful delete");
}
}
public void rename()
{
File f = getFile();
if (f != null)
{
outputPS.println("renaming "+ f.getAbsolutePath());
File f2 = getFile();
if (f.renameTo(f2))
outputPS.println(" Successful rename");
else
outputPS.println(" unSuccessful rename");
}
}
public void list()
{
File f = getFile();
if (f != null)
{
outputPS.println("Listing files for "+ f.getAbsolutePath());
if (f.exists())
{
String[] files = f.list();
if (files != null)
{
for (int i=0; i < files.length; i++)
outputPS.println(files[i]);
}
}
else
outputPS.println("list error - Non-existent:" + f.getAbsolutePath());
}
}
public void size()
{
File f = getFile();
if (f != null)
{
if (f.exists())
{
outputPS.print("size for "+ f.getAbsolutePath());
long len = f.length();
outputPS.println(" is = "+len);
}
else
outputPS.println("size error - Non-existent:" + f.getAbsolutePath());
}
}
public void lastModified()
{
File f = getFile();
if (f != null)
{
if (f.exists())
{
outputPS.println("lastModified for "+ f.getAbsolutePath());
long date = f.lastModified();
outputPS.println(" date="+new Date(date));
}
else
outputPS.println("lastModified error Non-existent:" + f.getAbsolutePath());
}
}
public void mkdir()
{
File f = getFile();
if (f != null)
{
if (f.mkdir())
outputPS.println("mkdir successful: " + f.getAbsolutePath());
else
outputPS.println("mkdir unsuccessful: " + f.getAbsolutePath());
}
}
public void createFile()
{
File f = getFile();
if (f!= null)
{
try {
PrintWriter pw = new PrintWriter(f);
String token = getNextToken();
while (token != null)
{
pw.println(token);
token = getNextToken();
}
pw.close();
outputPS.println("created file for "+ f.getAbsolutePath());
} catch (FileNotFoundException e) {
outputPS.println("createFile can't create: "+ f.getAbsolutePath());
}
}
}
public void printFile()
{
File f = getFile();
if (f != null)
{
try {
Scanner scan = new Scanner(f);
while (scan.hasNextLine())
{
outputPS.println(scan.nextLine());
}
scan.close();
outputPS.println("printed file for "+ f.getAbsolutePath());
} catch (FileNotFoundException e) {
outputPS.println("printFile can't open: "+ f.getAbsolutePath());
}
}
}
void printUsage()
{
outputPS.println("?");
outputPS.println("quit");
outputPS.println("delete filename");
outputPS.println("rename oldFilename newFilename");
outputPS.println("size filename");
outputPS.println("lastModified filename");
outputPS.println("list dir");
outputPS.println("printFile filename");
outputPS.println("createFile filename <remaining tokens written to file>");
outputPS.println("mkdir dir");
}
private String getNextToken()
{
if (parseCommand.hasMoreTokens())
return parseCommand.nextToken();
else
return null;
}
public File getFile()
{
File f = null;
String fileName = getNextToken();
if (fileName == null)
outputPS.println("Missing a File name");
else
f = new File(fileName);
return f;
}
public boolean processCommandLine(String line)
{
if (line == null)
return false;
boolean retval = true;
System.out.println("FileServer processing: " + line);
parseCommand = new StringTokenizer(line);
String cmd = getNextToken();
if (cmd == null)
{
outputPS.println("No command specified");
}
else
{
switch(cmd)
{
case "?":
printUsage();
break;
case "quit":
retval = false;
break;
case "delete":
delete();
break;
case "rename":
rename();
break;
case "size":
size();
break;
case "lastModified":
lastModified();
break;
case "list":
list();
break;
case "printFile":
printFile();
break;
case "createFile":
createFile();
break;
case "mkdir":
mkdir();
break;
default:
outputPS.println("Unrecognized command: "+cmd);
break;
}
}
outputPS.println("====================================");
outputPS.println();
return retval;
}
public void processStream(InputStream is, OutputStream os) {
System.out.println("FileServer.processStream begins");
Scanner input = new Scanner(is);
outputPS = new PrintStream(os);
boolean continueFlag = true;
while(continueFlag && input.hasNextLine())
{
String line = input.nextLine();
outputPS.println("***************************************");
outputPS.println(line);
continueFlag = processCommandLine(line);
}
input.close();
outputPS.close();
System.out.println("Exitting processStream");
}
public static void main(String[] args) {
FileServer fs = new FileServer();
fs.monitorServer();
System.out.println("Exitting FileServer");
}
}
------------------------------------------------------------------------
MotherServer.java
-------------------------------
package file_server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class MotherServer implements Runnable {
ServerSocket serverSocket = null;
int portNum=-1;
EchoServer echoServer= null;
boolean continueListening = true;
Thread myThread = null;
boolean startServer(int portNum, EchoServer echoServer)
{
this.portNum = portNum;
try {
serverSocket = new ServerSocket(portNum);
} catch (IOException e) {
System.out.println("ServerSocket connect error: " + e);
return false;
}
this.echoServer = echoServer;
myThread = new Thread(this);
myThread.start();
return true;
}
public void run() // This is where the Server executes
{
continueListening = true;
while(continueListening)
{
try {
Socket sock = serverSocket.accept();
echoServer.handleConnect(sock);
} catch (IOException e) {
System.out.println("ServerSocket accept error: " + e);
continueListening = false;
}
}
System.out.println("MyServer run thread exitting");
}
public void stopServer()
{
continueListening = false;
try {
serverSocket.close();
} catch (IOException e) {
System.out.println("stopServer error: " + e);
}
}
static String getHostInfo()
{
String retStr="";
try {
InetAddress iaddr = InetAddress.getLocalHost();
retStr= String.format("Host:%s ipaddr=%s",
iaddr.getHostName(), iaddr.getHostAddress());
}
catch (UnknownHostException e) {
retStr = e.toString();
}
return retStr;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.