Merge branch 'loggerclient' of flavien/Projet_JAVA_P2P_STRI2A into etape4
flavien's git/Projet_JAVA_P2P_STRI2A/pipeline/pr-master This commit looks good Details

pull/52/head
Flavien Haas 4 years ago committed by Gitea
commit 8d8ed294e8

@ -2,26 +2,28 @@ package clientP2P;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.net.Socket; import java.net.Socket;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import protocolP2P.ProtocolP2PPacketTCP; import protocolP2P.ProtocolP2PPacketTCP;
import protocolP2P.Payload; import protocolP2P.Payload;
import protocolP2P.LoadRequest; import protocolP2P.LoadRequest;
import protocolP2P.FilePart; import protocolP2P.FilePart;
import localException.InternalError; import localException.InternalError;
import localException.ProtocolError;
import localException.TransmissionError;
import localException.VersionError;
import localException.SizeError;
import localException.SocketClosed;
import remoteException.EmptyDirectory; import remoteException.EmptyDirectory;
import remoteException.EmptyFile; import remoteException.EmptyFile;
import localException.ProtocolError;
import remoteException.InternalRemoteError; import remoteException.InternalRemoteError;
import remoteException.VersionRemoteError; import remoteException.VersionRemoteError;
import localException.TransmissionError;
import remoteException.ProtocolRemoteError; import remoteException.ProtocolRemoteError;
import localException.VersionError;
import localException.SizeError;
import remoteException.NotFound; import remoteException.NotFound;
import java.nio.file.Files; import tools.Logger;
import java.io.File; import tools.LogLevel;
import java.nio.file.Paths;
import java.io.IOException;
import localException.SocketClosed;
/** Class to download file parts on tcp. /** Class to download file parts on tcp.
* @author Louis Royer * @author Louis Royer
@ -43,17 +45,19 @@ public class ClientDownloadPartTCP implements Runnable {
private String partsSubdir; private String partsSubdir;
private static final long MAX_PARTIAL_SIZE = 4096; private static final long MAX_PARTIAL_SIZE = 4096;
private ClientDownloadTCP manager; private ClientDownloadTCP manager;
private Logger logger;
/** Constructor with filename, socket, and part subdir /** Constructor with filename, socket, and part subdir
* @param filename name of file to download * @param filename name of file to download
* @param socket socket to use * @param socket socket to use
* @param partsSubdir directory to store .part files * @param partsSubdir directory to store .part files
*/ */
public ClientDownloadPartTCP(ClientDownloadTCP manager, String filename, Socket socket, String partsSubdir) { public ClientDownloadPartTCP(ClientDownloadTCP manager, String filename, Socket socket, String partsSubdir, Logger logger) {
this.manager = manager; this.manager = manager;
this.partsSubdir = partsSubdir; this.partsSubdir = partsSubdir;
this.filename = filename; this.filename = filename;
this.socket = socket; this.socket = socket;
this.logger = logger;
stop = false; stop = false;
failed = false; failed = false;
pendingTasks = new ArrayList<>(); pendingTasks = new ArrayList<>();
@ -97,10 +101,12 @@ public class ClientDownloadPartTCP implements Runnable {
} }
} }
System.err.println("Closing socket"); System.err.println("Closing socket");
logger.writeTCP("Closing socket", LogLevel.Info);
try{ try{
socket.close(); socket.close();
} catch(IOException e){ } catch(IOException e){
System.err.println("can't close socket"); System.err.println("can't close socket");
logger.writeTCP("can't close socket", LogLevel.Error);
} }
} }
@ -174,11 +180,13 @@ public class ClientDownloadPartTCP implements Runnable {
failed = downloadPart(p); failed = downloadPart(p);
if (failed) { if (failed) {
System.err.println("Error: DownloadPart failed."); System.err.println("Error: DownloadPart failed.");
logger.writeTCP("DownloadPart failed.", LogLevel.Error);
stop = true; stop = true;
} else if (toDoTasks.isEmpty()) { } else if (toDoTasks.isEmpty()) {
noTask = true; noTask = true;
} }
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
logger.writeTCP(e, LogLevel.Error);
noTask = true; noTask = true;
} }
@ -190,7 +198,8 @@ public class ClientDownloadPartTCP implements Runnable {
* @return ProtocolP2PPacketTCP used to send request * @return ProtocolP2PPacketTCP used to send request
*/ */
private ProtocolP2PPacketTCP reqPart(Long offset) { private ProtocolP2PPacketTCP reqPart(Long offset) {
System.err.println("New request: "+ offset); System.err.println("New request: " + offset);
logger.writeTCP("New request: " + offset, LogLevel.Info);
// maintain tracking of tasks // maintain tracking of tasks
if (toDoTasks.contains(offset)) { if (toDoTasks.contains(offset)) {
try { try {
@ -206,10 +215,12 @@ public class ClientDownloadPartTCP implements Runnable {
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
System.err.println("Error: reqPart interruptedException"); System.err.println("Error: reqPart interruptedException");
logger.writeTCP("reqPart interruptedException", LogLevel.Error);
return null; return null;
} }
} else { } else {
System.err.println("Error: reqPart (offset " + offset + " not in toDoTasks)"); System.err.println("Error: reqPart (offset " + offset + " not in toDoTasks)");
logger.writeTCP("reqPart (offset " + offset + " not in toDoTasks)", LogLevel.Error);
return null; return null;
} }
// send request // send request
@ -219,13 +230,16 @@ public class ClientDownloadPartTCP implements Runnable {
return d; return d;
} catch (InternalError e) { } catch (InternalError e) {
System.err.println("Error: reqPart internalError"); System.err.println("Error: reqPart internalError");
logger.writeTCP("reqPart internalError", LogLevel.Error);
return null; return null;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
System.err.println("Error: reqPart ioexception"); System.err.println("Error: reqPart ioexception");
logger.writeTCP("reqPart ioexception", LogLevel.Error);
return null; return null;
} catch (SocketClosed e){ } catch (SocketClosed e){
System.err.println("Error: reqPart SocketClosed"); System.err.println("Error: reqPart SocketClosed");
logger.writeTCP("reqPart SocketClosed", LogLevel.Error);
return null; return null;
} }
} }
@ -237,6 +251,7 @@ public class ClientDownloadPartTCP implements Runnable {
public boolean downloadPart(ProtocolP2PPacketTCP d) { public boolean downloadPart(ProtocolP2PPacketTCP d) {
if (d == null) { if (d == null) {
System.err.println("Error: downloadPart -> d is null."); System.err.println("Error: downloadPart -> d is null.");
logger.writeTCP("downloadPart -> d is null.", LogLevel.Error);
return true; return true;
} }
try { try {
@ -244,11 +259,13 @@ public class ClientDownloadPartTCP implements Runnable {
assert p instanceof FilePart : "This payload must be instance of FilePart"; assert p instanceof FilePart : "This payload must be instance of FilePart";
if (!(p instanceof FilePart)) { if (!(p instanceof FilePart)) {
System.err.println("Error: cannot get size."); System.err.println("Error: cannot get size.");
logger.writeTCP("cannot get size.", LogLevel.Error);
return true; return true;
} else { } else {
FilePart fp = (FilePart)p; FilePart fp = (FilePart)p;
if (!fp.getFilename().equals(filename)) { if (!fp.getFilename().equals(filename)) {
System.err.println("Error: wrong file received: `" + fp.getFilename() + "`"); System.err.println("Error: wrong file received: `" + fp.getFilename() + "`");
logger.writeTCP("wrong file received: `" + fp.getFilename() + "`", LogLevel.Error);
return true; return true;
} }
Long offset = Long.valueOf(fp.getOffset()); Long offset = Long.valueOf(fp.getOffset());
@ -257,9 +274,11 @@ public class ClientDownloadPartTCP implements Runnable {
Files.write(new File(partsSubdir + filename + "_" + offset + ".part").toPath(), fp.getPartialContent()); Files.write(new File(partsSubdir + filename + "_" + offset + ".part").toPath(), fp.getPartialContent());
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: cannot write file (" + partsSubdir + filename + "_" + offset + ".part)"); System.err.println("Error: cannot write file (" + partsSubdir + filename + "_" + offset + ".part)");
logger.writeTCP("cannot write file (" + partsSubdir + filename + "_" + offset + ".part)", LogLevel.Error);
} }
} else { } else {
System.err.println("Error: wrong file part received."); System.err.println("Error: wrong file part received.");
logger.writeTCP("wrong file part received.", LogLevel.Error);
return true; return true;
} }
try { try {
@ -275,48 +294,62 @@ public class ClientDownloadPartTCP implements Runnable {
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
System.err.println("Error: DownloadPart Interrupted exception"); System.err.println("Error: DownloadPart Interrupted exception");
logger.writeTCP("DownloadPart Interrupted exception", LogLevel.Error);
return true; return true;
} }
} }
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
System.err.println("Error: empty directory."); System.err.println("Error: empty directory.");
logger.writeTCP("empty directory.", LogLevel.Error);
return true; return true;
} catch (EmptyFile e) { } catch (EmptyFile e) {
System.err.println("Error: downloadPart emptyFile"); System.err.println("Error: downloadPart emptyFile");
logger.writeTCP("downloadPart emptyFile", LogLevel.Error);
// TODO: use more specific errors // TODO: use more specific errors
return true; return true;
} catch (ProtocolError e) { } catch (ProtocolError e) {
System.err.println("Error: downloadPart protocolError"); System.err.println("Error: downloadPart protocolError");
logger.writeTCP("downloadPart protocolError", LogLevel.Error);
return true; return true;
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
System.err.println("Error: downloadPart internalRemoteError"); System.err.println("Error: downloadPart internalRemoteError");
logger.writeTCP("downloadPart internalRemoteError", LogLevel.Error);
return true; return true;
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
System.err.println("Error: downloadPart versionRemoteError"); System.err.println("Error: downloadPart versionRemoteError");
logger.writeTCP("downloadPart versionRemoteError", LogLevel.Error);
return true; return true;
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
System.err.println("Error: downloadPart protocolRemoteError"); System.err.println("Error: downloadPart protocolRemoteError");
logger.writeTCP("downloadPart protocolRemoteError", LogLevel.Error);
return true; return true;
} catch (TransmissionError e) { } catch (TransmissionError e) {
System.err.println("Error: downloadPart transmissionError"); System.err.println("Error: downloadPart transmissionError");
logger.writeTCP("downloadPart transmissionError", LogLevel.Error);
return true; return true;
} catch (VersionError e) { } catch (VersionError e) {
System.err.println("Error: downloadPart versionError"); System.err.println("Error: downloadPart versionError");
logger.writeTCP("downloadPart versionError", LogLevel.Error);
return true; return true;
} catch (SizeError e) { } catch (SizeError e) {
System.err.println("Error: downloadPart sizeError"); System.err.println("Error: downloadPart sizeError");
logger.writeTCP("downloadPart sizeError", LogLevel.Error);
return true; return true;
} catch (NotFound e) { } catch (NotFound e) {
System.err.println("Error: downloadPart notFound"); System.err.println("Error: downloadPart notFound");
logger.writeTCP("downloadPart notFound", LogLevel.Error);
return true; return true;
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: downloadPart ioexception"); System.err.println("Error: downloadPart ioexception");
logger.writeTCP("downloadPart ioexception", LogLevel.Error);
return true; return true;
} catch (InternalError e) { } catch (InternalError e) {
System.err.println("Error: downloadPart internalError"); System.err.println("Error: downloadPart internalError");
logger.writeTCP("downloadPart internalError", LogLevel.Error);
return true; return true;
} catch (SocketClosed e){ } catch (SocketClosed e){
System.err.println("Error: downloadPart SocketClosed"); System.err.println("Error: downloadPart SocketClosed");
logger.writeTCP("downloadPart SocketClosed", LogLevel.Error);
return true; return true;
} }
return false; return false;

@ -21,6 +21,8 @@ import java.nio.file.Files;
import java.io.File; import java.io.File;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.io.IOException; import java.io.IOException;
import tools.Logger;
import tools.LogLevel;
/** Class to download file parts on udp. /** Class to download file parts on udp.
* @author Louis Royer * @author Louis Royer
@ -42,17 +44,19 @@ public class ClientDownloadPartUDP implements Runnable {
private String partsSubdir; private String partsSubdir;
private static final long MAX_PARTIAL_SIZE = 4096; private static final long MAX_PARTIAL_SIZE = 4096;
private ClientDownloadUDP manager; private ClientDownloadUDP manager;
private Logger logger;
/** Constructor with filename, socket, and part subdir /** Constructor with filename, socket, and part subdir
* @param filename name of file to download * @param filename name of file to download
* @param socket socket to use * @param socket socket to use
* @param partsSubdir directory to store .part files * @param partsSubdir directory to store .part files
*/ */
public ClientDownloadPartUDP(ClientDownloadUDP manager, String filename, DatagramSocket socket, String partsSubdir) { public ClientDownloadPartUDP(ClientDownloadUDP manager, String filename, DatagramSocket socket, String partsSubdir, Logger logger) {
this.manager = manager; this.manager = manager;
this.partsSubdir = partsSubdir; this.partsSubdir = partsSubdir;
this.filename = filename; this.filename = filename;
this.socket = socket; this.socket = socket;
this.logger = logger;
stop = false; stop = false;
failed = false; failed = false;
pendingTasks = new ArrayList<>(); pendingTasks = new ArrayList<>();
@ -96,6 +100,7 @@ public class ClientDownloadPartUDP implements Runnable {
} }
} }
System.err.println("Closing socket"); System.err.println("Closing socket");
logger.writeUDP("Closing socket", LogLevel.Info);
socket.close(); socket.close();
} }
@ -174,6 +179,7 @@ public class ClientDownloadPartUDP implements Runnable {
noTask = true; noTask = true;
} }
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
logger.writeUDP(e, LogLevel.Error);
noTask = true; noTask = true;
} }
@ -186,6 +192,7 @@ public class ClientDownloadPartUDP implements Runnable {
*/ */
private ProtocolP2PPacketUDP reqPart(Long offset) { private ProtocolP2PPacketUDP reqPart(Long offset) {
System.err.println("New request: "+ offset); System.err.println("New request: "+ offset);
logger.writeUDP("New request: "+ offset, LogLevel.Info);
// maintain tracking of tasks // maintain tracking of tasks
if (toDoTasks.contains(offset)) { if (toDoTasks.contains(offset)) {
try { try {
@ -201,10 +208,12 @@ public class ClientDownloadPartUDP implements Runnable {
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
System.err.println("Error: reqPart interruptedException"); System.err.println("Error: reqPart interruptedException");
logger.writeUDP("reqPart interruptedException", LogLevel.Error);
return null; return null;
} }
} else { } else {
System.err.println("Error: reqPart (offset " + offset + " not in toDoTasks)"); System.err.println("Error: reqPart (offset " + offset + " not in toDoTasks)");
logger.writeUDP("reqPart (offset " + offset + " not in toDoTasks)", LogLevel.Error);
return null; return null;
} }
// send request // send request
@ -214,10 +223,12 @@ public class ClientDownloadPartUDP implements Runnable {
return d; return d;
} catch (InternalError e) { } catch (InternalError e) {
System.err.println("Error: reqPart internalError"); System.err.println("Error: reqPart internalError");
logger.writeUDP("reqPart internalError", LogLevel.Error);
return null; return null;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
System.err.println("Error: reqPart ioexception"); System.err.println("Error: reqPart ioexception");
logger.writeUDP("reqPart ioexception", LogLevel.Error);
return null; return null;
} }
} }
@ -229,6 +240,7 @@ public class ClientDownloadPartUDP implements Runnable {
public boolean downloadPart(ProtocolP2PPacketUDP d) { public boolean downloadPart(ProtocolP2PPacketUDP d) {
if (d == null) { if (d == null) {
System.err.println("Error: downloadPart -> d is null."); System.err.println("Error: downloadPart -> d is null.");
logger.writeUDP("downloadPart -> d is null.", LogLevel.Error);
return true; return true;
} }
try { try {
@ -236,11 +248,13 @@ public class ClientDownloadPartUDP implements Runnable {
assert p instanceof FilePart : "This payload must be instance of FilePart"; assert p instanceof FilePart : "This payload must be instance of FilePart";
if (!(p instanceof FilePart)) { if (!(p instanceof FilePart)) {
System.err.println("Error: cannot get size."); System.err.println("Error: cannot get size.");
logger.writeUDP("cannot get size.", LogLevel.Error);
return true; return true;
} else { } else {
FilePart fp = (FilePart)p; FilePart fp = (FilePart)p;
if (!fp.getFilename().equals(filename)) { if (!fp.getFilename().equals(filename)) {
System.err.println("Error: wrong file received: `" + fp.getFilename() + "`"); System.err.println("Error: wrong file received: `" + fp.getFilename() + "`");
logger.writeUDP("wrong file received: `" + fp.getFilename() + "`", LogLevel.Error);
return true; return true;
} }
Long offset = Long.valueOf(fp.getOffset()); Long offset = Long.valueOf(fp.getOffset());
@ -249,9 +263,11 @@ public class ClientDownloadPartUDP implements Runnable {
Files.write(new File(partsSubdir + filename + "_" + offset + ".part").toPath(), fp.getPartialContent()); Files.write(new File(partsSubdir + filename + "_" + offset + ".part").toPath(), fp.getPartialContent());
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: cannot write file (" + partsSubdir + filename + "_" + offset + ".part)"); System.err.println("Error: cannot write file (" + partsSubdir + filename + "_" + offset + ".part)");
logger.writeUDP("cannot write file (" + partsSubdir + filename + "_" + offset + ".part)", LogLevel.Error);
} }
} else { } else {
System.err.println("Error: wrong file part received."); System.err.println("Error: wrong file part received.");
logger.writeUDP("wrong file part received.", LogLevel.Error);
return true; return true;
} }
try { try {
@ -267,45 +283,58 @@ public class ClientDownloadPartUDP implements Runnable {
} }
} catch(InterruptedException e) { } catch(InterruptedException e) {
System.err.println("Error: DownloadPart Interrupted exception"); System.err.println("Error: DownloadPart Interrupted exception");
logger.writeUDP("DownloadPart Interrupted exception", LogLevel.Error);
return true; return true;
} }
} }
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
System.err.println("Error: empty directory."); System.err.println("Error: empty directory.");
logger.writeUDP("empty directory.", LogLevel.Error);
return true; return true;
} catch (EmptyFile e) { } catch (EmptyFile e) {
System.err.println("Error: downloadPart emptyFile"); System.err.println("Error: downloadPart emptyFile");
logger.writeUDP("downloadPart emptyFile", LogLevel.Error);
// TODO: use more specific errors // TODO: use more specific errors
return true; return true;
} catch (ProtocolError e) { } catch (ProtocolError e) {
System.err.println("Error: downloadPart protocolError"); System.err.println("Error: downloadPart protocolError");
logger.writeUDP("downloadPart protocolError", LogLevel.Error);
return true; return true;
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
System.err.println("Error: downloadPart internalRemoteError"); System.err.println("Error: downloadPart internalRemoteError");
logger.writeUDP("downloadPart internalRemoteError", LogLevel.Error);
return true; return true;
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
System.err.println("Error: downloadPart versionRemoteError"); System.err.println("Error: downloadPart versionRemoteError");
logger.writeUDP("downloadPart versionRemoteError", LogLevel.Error);
return true; return true;
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
System.err.println("Error: downloadPart protocolRemoteError"); System.err.println("Error: downloadPart protocolRemoteError");
logger.writeUDP("downloadPart protocolRemoteError", LogLevel.Error);
return true; return true;
} catch (TransmissionError e) { } catch (TransmissionError e) {
System.err.println("Error: downloadPart transmissionError"); System.err.println("Error: downloadPart transmissionError");
logger.writeUDP("downloadPart transmissionError", LogLevel.Error);
return true; return true;
} catch (VersionError e) { } catch (VersionError e) {
System.err.println("Error: downloadPart versionError"); System.err.println("Error: downloadPart versionError");
logger.writeUDP("downloadPart versionError", LogLevel.Error);
return true; return true;
} catch (SizeError e) { } catch (SizeError e) {
System.err.println("Error: downloadPart sizeError"); System.err.println("Error: downloadPart sizeError");
logger.writeUDP("downloadPart sizeError", LogLevel.Error);
return true; return true;
} catch (NotFound e) { } catch (NotFound e) {
System.err.println("Error: downloadPart notFound"); System.err.println("Error: downloadPart notFound");
logger.writeUDP("downloadPart notFound", LogLevel.Error);
return true; return true;
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: downloadPart ioexception"); System.err.println("Error: downloadPart ioexception");
logger.writeUDP("downloadPart ioexception", LogLevel.Error);
return true; return true;
} catch (InternalError e) { } catch (InternalError e) {
System.err.println("Error: downloadPart internalError"); System.err.println("Error: downloadPart internalError");
logger.writeUDP("downloadPart internalError", LogLevel.Error);
return true; return true;
} }
return false; return false;

@ -1,35 +1,38 @@
package clientP2P; package clientP2P;
import clientP2P.ClientDownloadPartTCP;
import tools.HostItem;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.StandardCopyOption;
import remoteException.EmptyDirectory; import remoteException.EmptyDirectory;
import remoteException.EmptyFile; import remoteException.EmptyFile;
import remoteException.VersionRemoteError; import remoteException.VersionRemoteError;
import remoteException.ProtocolRemoteError; import remoteException.ProtocolRemoteError;
import remoteException.NotFound; import remoteException.NotFound;
import remoteException.InternalRemoteError; import remoteException.InternalRemoteError;
import protocolP2P.HashAlgorithm;
import protocolP2P.HashResponse;
import protocolP2P.HashRequest;
import protocolP2P.ProtocolP2PPacketTCP;
import protocolP2P.Payload;
import localException.ProtocolError; import localException.ProtocolError;
import localException.InternalError; import localException.InternalError;
import localException.TransmissionError; import localException.TransmissionError;
import localException.SizeError; import localException.SizeError;
import localException.VersionError; import localException.VersionError;
import localException.SocketClosed;
import protocolP2P.HashAlgorithm;
import protocolP2P.HashResponse;
import protocolP2P.HashRequest;
import protocolP2P.ProtocolP2PPacketTCP;
import protocolP2P.Payload;
import protocolP2P.FilePart; import protocolP2P.FilePart;
import protocolP2P.LoadRequest; import protocolP2P.LoadRequest;
import java.io.IOException; import clientP2P.ClientDownloadPartTCP;
import java.nio.file.Files; import tools.HostItem;
import java.io.File; import tools.Logger;
import java.nio.file.Paths; import tools.LogLevel;
import java.nio.file.StandardOpenOption;
import java.nio.file.StandardCopyOption;
import localException.SocketClosed;
/** Class to download file from tcp /** Class to download file from tcp
* @author Louis Royer * @author Louis Royer
@ -51,6 +54,7 @@ public class ClientDownloadTCP implements Runnable {
private String partsSubdir; private String partsSubdir;
private String dirStorage; private String dirStorage;
private boolean success = false; private boolean success = false;
private Logger logger;
/** Constructor with parameters: filename, list of hosts, parts subdirectory and dirStorage /** Constructor with parameters: filename, list of hosts, parts subdirectory and dirStorage
* @param filename name of file to download * @param filename name of file to download
@ -58,11 +62,12 @@ public class ClientDownloadTCP implements Runnable {
* @param partsSubdir directory to store .part files * @param partsSubdir directory to store .part files
* @param dirStorage directory to write assembled file * @param dirStorage directory to write assembled file
*/ */
public ClientDownloadTCP(String filename, List<HostItem> hostList, String partsSubdir, String dirStorage) { public ClientDownloadTCP(String filename, List<HostItem> hostList, String partsSubdir, String dirStorage, Logger logger) {
this.partsSubdir = partsSubdir; this.partsSubdir = partsSubdir;
this.dirStorage = dirStorage; this.dirStorage = dirStorage;
this.filename = filename; this.filename = filename;
this.hostList = hostList; this.hostList = hostList;
this.logger = logger;
this.stop = false; this.stop = false;
} }
@ -79,9 +84,11 @@ public class ClientDownloadTCP implements Runnable {
init(); init();
if (stop) { if (stop) {
System.err.println("File is smaller than part max size."); System.err.println("File is smaller than part max size.");
logger.writeTCP("File is smaller than part max size.", LogLevel.Info);
hostList.get(0).closeTCPSocket(); hostList.get(0).closeTCPSocket();
} else { } else {
System.err.println("File is bigger than part max size."); System.err.println("File is bigger than part max size.");
logger.writeTCP("File is bigger than part max size.", LogLevel.Info);
purgeList(); purgeList();
initThreads(); initThreads();
while(!stop) { while(!stop) {
@ -91,9 +98,11 @@ public class ClientDownloadTCP implements Runnable {
} }
} }
System.err.println("Reassembling file parts."); System.err.println("Reassembling file parts.");
logger.writeTCP("Reassembling file parts.", LogLevel.Info);
reassembleFile(); reassembleFile();
} catch(InternalError e) { } catch(InternalError e) {
System.err.println("Error while downloading file. Aborting."); System.err.println("Error while downloading file. Aborting.");
logger.writeTCP("Error while downloading file. Aborting.", LogLevel.Error);
} finally { } finally {
stopTasks(); stopTasks();
} }
@ -103,13 +112,14 @@ public class ClientDownloadTCP implements Runnable {
*/ */
private void initThreads() { private void initThreads() {
for(HostItem hostItem: hostList) { for(HostItem hostItem: hostList) {
sockList.add(new ClientDownloadPartTCP(this, filename, hostItem.getTCPSocket(), partsSubdir)); sockList.add(new ClientDownloadPartTCP(this, filename, hostItem.getTCPSocket(), partsSubdir, logger));
} }
for(ClientDownloadPartTCP c: sockList) { for(ClientDownloadPartTCP c: sockList) {
Thread t = new Thread(c); Thread t = new Thread(c);
t.start(); t.start();
} }
System.err.println("Threads initialized"); System.err.println("Threads initialized");
logger.writeTCP("Threads initialized", LogLevel.Info);
} }
/** Remove tasks from failed threads. Update done status. /** Remove tasks from failed threads. Update done status.
@ -133,15 +143,18 @@ public class ClientDownloadTCP implements Runnable {
} }
} }
System.err.println("Task check status: " + offsetsToAsk.size() + " to asks, " + offsetsPending.size() + " pending"); System.err.println("Task check status: " + offsetsToAsk.size() + " to asks, " + offsetsPending.size() + " pending");
logger.writeTCP("Task check status: " + offsetsToAsk.size() + " to asks, " + offsetsPending.size() + " pending", LogLevel.Info);
if (offsetsToAsk.isEmpty() && offsetsPending.isEmpty()) { if (offsetsToAsk.isEmpty() && offsetsPending.isEmpty()) {
stop = true; stop = true;
} }
if (sockList.size() == 0) { if (sockList.size() == 0) {
System.err.println("No thread working"); System.err.println("No thread working");
logger.writeTCP("No thread working", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -157,6 +170,7 @@ public class ClientDownloadTCP implements Runnable {
offsetsPending.add(offset); offsetsPending.add(offset);
System.err.println("Assigned task "+ offset); System.err.println("Assigned task "+ offset);
} catch(InterruptedException e) { } catch(InterruptedException e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -168,7 +182,9 @@ public class ClientDownloadTCP implements Runnable {
for(ClientDownloadPartTCP c : sockList) { for(ClientDownloadPartTCP c : sockList) {
try { try {
c.setStop(); c.setStop();
} catch (InterruptedException e) {} } catch (InterruptedException e) {
logger.writeTCP(e, LogLevel.Error);
}
} }
} }
@ -193,32 +209,44 @@ public class ClientDownloadTCP implements Runnable {
hash = ((HashResponse)pHash).getHash(HashAlgorithm.SHA512); hash = ((HashResponse)pHash).getHash(HashAlgorithm.SHA512);
} }
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
logger.writeTCP(e, LogLevel.Error);
hash = new byte[0]; hash = new byte[0];
} catch (NotFound e) { } catch (NotFound e) {
logger.writeTCP(e, LogLevel.Error);
hash = new byte[0]; hash = new byte[0];
// TODO: use more specific errors // TODO: use more specific errors
} catch (EmptyFile e) { } catch (EmptyFile e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (ProtocolError e) { } catch (ProtocolError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (TransmissionError e) { } catch (TransmissionError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionError e) { } catch (VersionError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (SizeError e) { } catch (SizeError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
return hash; return hash;
} catch (IOException e) { } catch (IOException e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (SocketClosed e){ } catch (SocketClosed e){
System.err.println("getHashSum512 : SocketClosed"); System.err.println("getHashSum512 : SocketClosed");
logger.writeTCP("getHashSum512 : SocketClosed", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -248,6 +276,7 @@ public class ClientDownloadTCP implements Runnable {
hostList.remove(host); hostList.remove(host);
} }
System.err.println("Host list purge: done"); System.err.println("Host list purge: done");
logger.writeTCP("Host list purge: done", LogLevel.Info);
} }
/** Getter for hash512sum /** Getter for hash512sum
@ -269,6 +298,7 @@ public class ClientDownloadTCP implements Runnable {
hash512 = getHashSum512(hostList.get(0)); hash512 = getHashSum512(hostList.get(0));
if (hash512.length == 0) { if (hash512.length == 0) {
System.err.println("Error: no hash512sum support."); System.err.println("Error: no hash512sum support.");
logger.writeTCP("no hash512sum support.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
@ -278,6 +308,7 @@ public class ClientDownloadTCP implements Runnable {
offsetsToAsk.add(Long.valueOf(i)); offsetsToAsk.add(Long.valueOf(i));
} }
System.err.println("Adding tasks: done"); System.err.println("Adding tasks: done");
logger.writeTCP("Adding tasks: done", LogLevel.Info);
} }
} }
@ -293,11 +324,13 @@ public class ClientDownloadTCP implements Runnable {
assert p instanceof FilePart : "This payload must be instance of FilePart"; assert p instanceof FilePart : "This payload must be instance of FilePart";
if (!(p instanceof FilePart)) { if (!(p instanceof FilePart)) {
System.err.println("Error: cannot get size."); System.err.println("Error: cannot get size.");
logger.writeTCP("cannot get size.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} else { } else {
FilePart fp = (FilePart)p; FilePart fp = (FilePart)p;
if (!fp.getFilename().equals(filename)) { if (!fp.getFilename().equals(filename)) {
System.err.println("Error: wrong file received: `" + fp.getFilename() + "`"); System.err.println("Error: wrong file received: `" + fp.getFilename() + "`");
logger.writeTCP("wrong file received: `" + fp.getFilename() + "`", LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} }
if (fp.getOffset() == 0) { if (fp.getOffset() == 0) {
@ -305,6 +338,7 @@ public class ClientDownloadTCP implements Runnable {
Files.write(new File(partsSubdir + filename + "_0.part").toPath(), fp.getPartialContent()); Files.write(new File(partsSubdir + filename + "_0.part").toPath(), fp.getPartialContent());
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: cannot write file (" + partsSubdir + filename + "_0.part)"); System.err.println("Error: cannot write file (" + partsSubdir + filename + "_0.part)");
logger.writeTCP("cannot write file (" + partsSubdir + filename + "_0.part)", LogLevel.Error);
} }
size = fp.getTotalSize(); size = fp.getTotalSize();
if (fp.getPartialContent().length == size) { if (fp.getPartialContent().length == size) {
@ -312,36 +346,49 @@ public class ClientDownloadTCP implements Runnable {
} }
} else { } else {
System.err.println("Error: wrong file part received."); System.err.println("Error: wrong file part received.");
logger.writeTCP("wrong file part received.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
System.err.println("Error: empty directory."); System.err.println("Error: empty directory.");
logger.writeTCP("empty directory.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (EmptyFile e) { } catch (EmptyFile e) {
logger.writeTCP(e, LogLevel.Error);
// TODO: use more specific errors // TODO: use more specific errors
throw new InternalError(); throw new InternalError();
} catch (ProtocolError e) { } catch (ProtocolError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (TransmissionError e) { } catch (TransmissionError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionError e) { } catch (VersionError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (SizeError e) { } catch (SizeError e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (NotFound e) { } catch (NotFound e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} catch (IOException e) { } catch (IOException e) {
logger.writeTCP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (SocketClosed e){ } catch (SocketClosed e){
System.err.println("setSize : SocketClosed"); System.err.println("setSize : SocketClosed");
logger.writeTCP("setSize : SocketClosed", LogLevel.Error);
} }
} }
@ -362,6 +409,7 @@ public class ClientDownloadTCP implements Runnable {
do { do {
if (firstPart) { if (firstPart) {
System.err.println("Reassembling: First part"); System.err.println("Reassembling: First part");
logger.writeTCP("Reassembling: First part", LogLevel.Info);
try { try {
// create file // create file
Files.copy(new File(partsSubdir + filename + "_" + nextOffset + ".part").toPath(), new File(dirStorage + filename).toPath(), StandardCopyOption.REPLACE_EXISTING); Files.copy(new File(partsSubdir + filename + "_" + nextOffset + ".part").toPath(), new File(dirStorage + filename).toPath(), StandardCopyOption.REPLACE_EXISTING);
@ -369,11 +417,13 @@ public class ClientDownloadTCP implements Runnable {
firstPart = false; firstPart = false;
} catch (IOException e) { } catch (IOException e) {
System.err.println("Reassembling: aborting on first part"); System.err.println("Reassembling: aborting on first part");
logger.writeTCP("Reassembling: aborting on first part", LogLevel.Error);
abort = true; abort = true;
} }
} else if (nextOffset >= size) { } else if (nextOffset >= size) {
success = true; success = true;
System.err.println("Reassembling: success"); System.err.println("Reassembling: success");
logger.writeTCP("Reassembling: success", LogLevel.Info);
} else { } else {
// append to file // append to file
try { try {
@ -382,6 +432,7 @@ public class ClientDownloadTCP implements Runnable {
} catch (IOException e) { } catch (IOException e) {
abort = true; abort = true;
System.err.println("Aborting: bad number " + nextOffset); System.err.println("Aborting: bad number " + nextOffset);
logger.writeTCP("Aborting: bad number " + nextOffset, LogLevel.Error);
} }
} }
} while((!success) && (!abort)); } while((!success) && (!abort));

@ -1,10 +1,20 @@
package clientP2P; package clientP2P;
import clientP2P.ClientDownloadPartUDP;
import tools.HostItem;
import java.util.List; import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Random; import java.util.Random;
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.StandardCopyOption;
import localException.ProtocolError;
import localException.InternalError;
import localException.TransmissionError;
import localException.SizeError;
import localException.VersionError;
import remoteException.EmptyDirectory; import remoteException.EmptyDirectory;
import remoteException.EmptyFile; import remoteException.EmptyFile;
import remoteException.VersionRemoteError; import remoteException.VersionRemoteError;
@ -16,19 +26,13 @@ import protocolP2P.HashResponse;
import protocolP2P.HashRequest; import protocolP2P.HashRequest;
import protocolP2P.ProtocolP2PPacketUDP; import protocolP2P.ProtocolP2PPacketUDP;
import protocolP2P.Payload; import protocolP2P.Payload;
import localException.ProtocolError;
import localException.InternalError;
import localException.TransmissionError;
import localException.SizeError;
import localException.VersionError;
import protocolP2P.FilePart; import protocolP2P.FilePart;
import protocolP2P.LoadRequest; import protocolP2P.LoadRequest;
import java.io.IOException; import clientP2P.ClientDownloadPartUDP;
import java.nio.file.Files; import tools.HostItem;
import java.io.File; import tools.Logger;
import java.nio.file.Paths; import tools.LogLevel;
import java.nio.file.StandardOpenOption;
import java.nio.file.StandardCopyOption;
/** Class to download file from udp /** Class to download file from udp
* @author Louis Royer * @author Louis Royer
@ -50,6 +54,7 @@ public class ClientDownloadUDP implements Runnable {
private String partsSubdir; private String partsSubdir;
private String dirStorage; private String dirStorage;
private boolean success = false; private boolean success = false;
private Logger logger;
/** Constructor with parameters: filename, list of hosts, parts subdirectory and dirStorage /** Constructor with parameters: filename, list of hosts, parts subdirectory and dirStorage
* @param filename name of file to download * @param filename name of file to download
@ -57,11 +62,12 @@ public class ClientDownloadUDP implements Runnable {
* @param partsSubdir directory to store .part files * @param partsSubdir directory to store .part files
* @param dirStorage directory to write assembled file * @param dirStorage directory to write assembled file
*/ */
public ClientDownloadUDP(String filename, List<HostItem> hostList, String partsSubdir, String dirStorage) { public ClientDownloadUDP(String filename, List<HostItem> hostList, String partsSubdir, String dirStorage, Logger logger) {
this.partsSubdir = partsSubdir; this.partsSubdir = partsSubdir;
this.dirStorage = dirStorage; this.dirStorage = dirStorage;
this.filename = filename; this.filename = filename;
this.hostList = hostList; this.hostList = hostList;
this.logger = logger;
this.stop = false; this.stop = false;
} }
@ -78,9 +84,11 @@ public class ClientDownloadUDP implements Runnable {
init(); init();
if (stop) { if (stop) {
System.err.println("File is smaller than part max size."); System.err.println("File is smaller than part max size.");
logger.writeUDP("File is smaller than part max size.", LogLevel.Info);
hostList.get(0).closeUDPSocket(); hostList.get(0).closeUDPSocket();
} else { } else {
System.err.println("File is bigger than part max size."); System.err.println("File is bigger than part max size.");
logger.writeUDP("File is bigger than part max size.", LogLevel.Info);
purgeList(); purgeList();
initThreads(); initThreads();
while(!stop) { while(!stop) {
@ -90,9 +98,11 @@ public class ClientDownloadUDP implements Runnable {
} }
} }
System.err.println("Reassembling file parts."); System.err.println("Reassembling file parts.");
logger.writeUDP("Reassembling file parts.", LogLevel.Info);
reassembleFile(); reassembleFile();
} catch(InternalError e) { } catch(InternalError e) {
System.err.println("Error while downloading file. Aborting."); System.err.println("Error while downloading file. Aborting.");
logger.writeUDP("Error while downloading file. Aborting.", LogLevel.Error);
} finally { } finally {
stopTasks(); stopTasks();
} }
@ -102,13 +112,14 @@ public class ClientDownloadUDP implements Runnable {
*/ */
private void initThreads() { private void initThreads() {
for(HostItem hostItem: hostList) { for(HostItem hostItem: hostList) {
sockList.add(new ClientDownloadPartUDP(this, filename, hostItem.getUDPSocket(), partsSubdir)); sockList.add(new ClientDownloadPartUDP(this, filename, hostItem.getUDPSocket(), partsSubdir, logger));
} }
for(ClientDownloadPartUDP c: sockList) { for(ClientDownloadPartUDP c: sockList) {
Thread t = new Thread(c); Thread t = new Thread(c);
t.start(); t.start();
} }
System.err.println("Threads initialized"); System.err.println("Threads initialized");
logger.writeUDP("Threads initialized", LogLevel.Error);
} }
/** Remove tasks from failed threads. Update done status. /** Remove tasks from failed threads. Update done status.
@ -132,11 +143,13 @@ public class ClientDownloadUDP implements Runnable {
} }
} }
System.err.println("Task check status: " + offsetsToAsk.size() + " to asks, " + offsetsPending.size() + " pending"); System.err.println("Task check status: " + offsetsToAsk.size() + " to asks, " + offsetsPending.size() + " pending");
logger.writeUDP("Task check status: " + offsetsToAsk.size() + " to asks, " + offsetsPending.size() + " pending", LogLevel.Info);
if (offsetsToAsk.isEmpty() && offsetsPending.isEmpty()) { if (offsetsToAsk.isEmpty() && offsetsPending.isEmpty()) {
stop = true; stop = true;
} }
if (sockList.size() == 0) { if (sockList.size() == 0) {
System.err.println("No thread working"); System.err.println("No thread working");
logger.writeUDP("No thread working", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -155,7 +168,9 @@ public class ClientDownloadUDP implements Runnable {
sockList.get(rand.nextInt(sockList.size())).assignTask(offset); sockList.get(rand.nextInt(sockList.size())).assignTask(offset);
offsetsPending.add(offset); offsetsPending.add(offset);
System.err.println("Assigned task "+ offset); System.err.println("Assigned task "+ offset);
logger.writeUDP("Assigned task "+ offset, LogLevel.Info);
} catch(InterruptedException e) { } catch(InterruptedException e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -167,7 +182,9 @@ public class ClientDownloadUDP implements Runnable {
for(ClientDownloadPartUDP c : sockList) { for(ClientDownloadPartUDP c : sockList) {
try { try {
c.setStop(); c.setStop();
} catch (InterruptedException e) {} } catch (InterruptedException e) {
logger.writeUDP(e, LogLevel.Error);
}
} }
} }
@ -192,29 +209,40 @@ public class ClientDownloadUDP implements Runnable {
hash = ((HashResponse)pHash).getHash(HashAlgorithm.SHA512); hash = ((HashResponse)pHash).getHash(HashAlgorithm.SHA512);
} }
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
logger.writeUDP(e, LogLevel.Error);
hash = new byte[0]; hash = new byte[0];
} catch (NotFound e) { } catch (NotFound e) {
logger.writeUDP(e, LogLevel.Error);
hash = new byte[0]; hash = new byte[0];
// TODO: use more specific errors // TODO: use more specific errors
} catch (EmptyFile e) { } catch (EmptyFile e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (ProtocolError e) { } catch (ProtocolError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (TransmissionError e) { } catch (TransmissionError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionError e) { } catch (VersionError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (SizeError e) { } catch (SizeError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
return hash; return hash;
} catch (IOException e) { } catch (IOException e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -244,6 +272,7 @@ public class ClientDownloadUDP implements Runnable {
hostList.remove(host); hostList.remove(host);
} }
System.err.println("Host list purge: done"); System.err.println("Host list purge: done");
logger.writeUDP("Host list purge: done", LogLevel.Info);
} }
/** Getter for hash512sum /** Getter for hash512sum
@ -265,6 +294,7 @@ public class ClientDownloadUDP implements Runnable {
hash512 = getHashSum512(hostList.get(0)); hash512 = getHashSum512(hostList.get(0));
if (hash512.length == 0) { if (hash512.length == 0) {
System.err.println("Error: no hash512sum support."); System.err.println("Error: no hash512sum support.");
logger.writeUDP("no hash512sum support.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
@ -274,6 +304,7 @@ public class ClientDownloadUDP implements Runnable {
offsetsToAsk.add(Long.valueOf(i)); offsetsToAsk.add(Long.valueOf(i));
} }
System.err.println("Adding tasks: done"); System.err.println("Adding tasks: done");
logger.writeUDP("Adding tasks: done", LogLevel.Info);
} }
} }
@ -289,11 +320,13 @@ public class ClientDownloadUDP implements Runnable {
assert p instanceof FilePart : "This payload must be instance of FilePart"; assert p instanceof FilePart : "This payload must be instance of FilePart";
if (!(p instanceof FilePart)) { if (!(p instanceof FilePart)) {
System.err.println("Error: cannot get size."); System.err.println("Error: cannot get size.");
logger.writeUDP("cannot get size.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} else { } else {
FilePart fp = (FilePart)p; FilePart fp = (FilePart)p;
if (!fp.getFilename().equals(filename)) { if (!fp.getFilename().equals(filename)) {
System.err.println("Error: wrong file received: `" + fp.getFilename() + "`"); System.err.println("Error: wrong file received: `" + fp.getFilename() + "`");
logger.writeUDP("wrong file received: `" + fp.getFilename() + "`", LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} }
if (fp.getOffset() == 0) { if (fp.getOffset() == 0) {
@ -301,6 +334,7 @@ public class ClientDownloadUDP implements Runnable {
Files.write(new File(partsSubdir + filename + "_0.part").toPath(), fp.getPartialContent()); Files.write(new File(partsSubdir + filename + "_0.part").toPath(), fp.getPartialContent());
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: cannot write file (" + partsSubdir + filename + "_0.part)"); System.err.println("Error: cannot write file (" + partsSubdir + filename + "_0.part)");
logger.writeUDP("cannot write file (" + partsSubdir + filename + "_0.part)", LogLevel.Error);
} }
size = fp.getTotalSize(); size = fp.getTotalSize();
if (fp.getPartialContent().length == size) { if (fp.getPartialContent().length == size) {
@ -308,33 +342,45 @@ public class ClientDownloadUDP implements Runnable {
} }
} else { } else {
System.err.println("Error: wrong file part received."); System.err.println("Error: wrong file part received.");
logger.writeUDP("wrong file part received.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
System.err.println("Error: empty directory."); System.err.println("Error: empty directory.");
logger.writeUDP("empty directory.", LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (EmptyFile e) { } catch (EmptyFile e) {
logger.writeUDP(e, LogLevel.Error);
// TODO: use more specific errors // TODO: use more specific errors
throw new InternalError(); throw new InternalError();
} catch (ProtocolError e) { } catch (ProtocolError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (TransmissionError e) { } catch (TransmissionError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (VersionError e) { } catch (VersionError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (SizeError e) { } catch (SizeError e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} catch (NotFound e) { } catch (NotFound e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} catch (IOException e) { } catch (IOException e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -356,6 +402,7 @@ public class ClientDownloadUDP implements Runnable {
do { do {
if (firstPart) { if (firstPart) {
System.err.println("Reassembling: First part"); System.err.println("Reassembling: First part");
logger.writeUDP("Reassembling: First part", LogLevel.Info);
try { try {
// create file // create file
Files.copy(new File(partsSubdir + filename + "_" + nextOffset + ".part").toPath(), new File(dirStorage + filename).toPath(), StandardCopyOption.REPLACE_EXISTING); Files.copy(new File(partsSubdir + filename + "_" + nextOffset + ".part").toPath(), new File(dirStorage + filename).toPath(), StandardCopyOption.REPLACE_EXISTING);
@ -363,11 +410,13 @@ public class ClientDownloadUDP implements Runnable {
firstPart = false; firstPart = false;
} catch (IOException e) { } catch (IOException e) {
System.err.println("Reassembling: aborting on first part"); System.err.println("Reassembling: aborting on first part");
logger.writeUDP("Reassembling: aborting on first part", LogLevel.Warning);
abort = true; abort = true;
} }
} else if (nextOffset >= size) { } else if (nextOffset >= size) {
success = true; success = true;
System.err.println("Reassembling: success"); System.err.println("Reassembling: success");
logger.writeUDP("Reassembling: success", LogLevel.Info);
} else { } else {
// append to file // append to file
try { try {
@ -376,6 +425,7 @@ public class ClientDownloadUDP implements Runnable {
} catch (IOException e) { } catch (IOException e) {
abort = true; abort = true;
System.err.println("Aborting: bad number " + nextOffset); System.err.println("Aborting: bad number " + nextOffset);
logger.writeUDP("Aborting: bad number " + nextOffset, LogLevel.Error);
} }
} }
} while((!success) && (!abort)); } while((!success) && (!abort));

@ -1,25 +1,28 @@
package clientP2P; package clientP2P;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import localException.InternalError; import localException.InternalError;
import localException.ProtocolError; import localException.ProtocolError;
import localException.SizeError; import localException.SizeError;
import localException.TransmissionError; import localException.TransmissionError;
import localException.VersionError; import localException.VersionError;
import localException.SocketClosed;
import remoteException.EmptyFile; import remoteException.EmptyFile;
import remoteException.EmptyDirectory; import remoteException.EmptyDirectory;
import remoteException.InternalRemoteError; import remoteException.InternalRemoteError;
import remoteException.NotFound; import remoteException.NotFound;
import remoteException.ProtocolRemoteError; import remoteException.ProtocolRemoteError;
import remoteException.VersionRemoteError; import remoteException.VersionRemoteError;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import tools.HostItem;
import protocolP2P.ProtocolP2PPacketTCP; import protocolP2P.ProtocolP2PPacketTCP;
import protocolP2P.Payload; import protocolP2P.Payload;
import protocolP2P.RequestResponseCode; import protocolP2P.RequestResponseCode;
@ -29,10 +32,10 @@ import protocolP2P.LoadRequest;
import protocolP2P.HashAlgorithm; import protocolP2P.HashAlgorithm;
import protocolP2P.HashRequest; import protocolP2P.HashRequest;
import protocolP2P.HashResponse; import protocolP2P.HashResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import clientP2P.ClientDownloadTCP; import clientP2P.ClientDownloadTCP;
import localException.SocketClosed; import tools.HostItem;
import tools.Logger;
import tools.LogLevel;
/** Implementation of P2P-JAVA-PROJECT CLIENT /** Implementation of P2P-JAVA-PROJECT CLIENT
* @author Louis Royer * @author Louis Royer
@ -44,16 +47,18 @@ public class ClientManagementTCP implements Runnable {
private String baseDirectory; private String baseDirectory;
private String partsSubdir; private String partsSubdir;
private List<HostItem> hostList; private List<HostItem> hostList;
private Logger logger;
/** Constructor for TCP implementation, with baseDirectory and TCPPort parameters. /** Constructor for TCP implementation, with baseDirectory and TCPPort parameters.
* @param baseDirectory the root directory where files are stored * @param baseDirectory the root directory where files are stored
* @param host hostname of the server * @param host hostname of the server
* @param TCPPort the server will listen on this port * @param TCPPort the server will listen on this port
*/ */
public ClientManagementTCP(String baseDirectory, List<HostItem> hostList, String partsSubdir) { public ClientManagementTCP(String baseDirectory, List<HostItem> hostList, String partsSubdir, Logger logger) {
this.baseDirectory = baseDirectory; this.baseDirectory = baseDirectory;
this.hostList = hostList; this.hostList = hostList;
this.partsSubdir = partsSubdir; this.partsSubdir = partsSubdir;
this.logger = logger;
} }
/** Implementation of Runnable /** Implementation of Runnable
@ -70,33 +75,47 @@ public class ClientManagementTCP implements Runnable {
System.out.println("Name of the file to download:"); System.out.println("Name of the file to download:");
String f = scanner.nextLine(); String f = scanner.nextLine();
download(f); download(f);
System.out.println("File sucessfully downloaded"); System.out.println("File " + f + " sucessfully downloaded");
logger.writeTCP("File " + f + " sucessfully downloaded", LogLevel.Info);
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
System.err.println("Error: Server has no file in directory"); System.err.println("Error: Server has no file in directory");
logger.writeTCP("Error: Server has no file in directory", LogLevel.Error);
} catch (InternalError e) { } catch (InternalError e) {
System.err.println("Error: Client internal error"); System.err.println("Error: Client internal error");
logger.writeTCP("Error: Client internal error", LogLevel.Error);
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
System.err.println("Error: Server host is unknown"); System.err.println("Error: Server host is unknown");
logger.writeTCP("Error: Server host is unknown", LogLevel.Error);
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: Request cannot be send or response cannot be received"); System.err.println("Error: Request cannot be send or response cannot be received");
logger.writeTCP("Error: Request cannot be send or response cannot be received", LogLevel.Error);
} catch (TransmissionError e) { } catch (TransmissionError e) {
System.err.println("Error: Message received is too big"); System.err.println("Error: Message received is too big");
logger.writeTCP("Error: Message received is too big", LogLevel.Error);
} catch (ProtocolError e) { } catch (ProtocolError e) {
System.err.println("Error: Cannot decode servers response"); System.err.println("Error: Cannot decode servers response");
logger.writeTCP("Error: Cannot decode servers response", LogLevel.Error);
} catch (VersionError e) { } catch (VersionError e) {
System.err.println("Error: Servers response use bad version of the protocol"); System.err.println("Error: Servers response use bad version of the protocol");
logger.writeTCP("Error: Servers response use bad version of the protocol", LogLevel.Error);
} catch (SizeError e) { } catch (SizeError e) {
System.err.println("Error: Cannot handle this packets because of internal representation limitations of numbers on the client"); System.err.println("Error: Cannot handle this packets because of internal representation limitations of numbers on the client");
logger.writeTCP("Error: Cannot handle this packets because of internal representation limitations of numbers on the client", LogLevel.Error);
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
System.err.println("Error: Server internal error"); System.err.println("Error: Server internal error");
logger.writeTCP("Error: Server internal error", LogLevel.Error);
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
System.err.println("Error: Server cannot decode clients request"); System.err.println("Error: Server cannot decode clients request");
logger.writeTCP("Error: Server cannot decode clients request", LogLevel.Error);
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
System.err.println("Error: Server cannot decode this version of the protocol"); System.err.println("Error: Server cannot decode this version of the protocol");
logger.writeTCP("Error: Server cannot decode this version of the protocol", LogLevel.Error);
} catch (NotFound e) { } catch (NotFound e) {
System.err.println("Error: Server has not this file in directory"); System.err.println("Error: Server has not this file in directory");
logger.writeTCP("Error: Server has not this file in directory", LogLevel.Error);
} catch (EmptyFile e) { } catch (EmptyFile e) {
System.err.println("Error: File is empty"); System.err.println("Error: File is empty");
logger.writeTCP("Error: File is empty", LogLevel.Error);
} }
} }
@ -116,7 +135,7 @@ public class ClientManagementTCP implements Runnable {
* @throws EmptyFile * @throws EmptyFile
*/ */
private void download(String filename) throws EmptyFile, NotFound, InternalError, UnknownHostException, IOException, TransmissionError, ProtocolError, VersionError, SizeError, InternalRemoteError, ProtocolRemoteError, VersionRemoteError { private void download(String filename) throws EmptyFile, NotFound, InternalError, UnknownHostException, IOException, TransmissionError, ProtocolError, VersionError, SizeError, InternalRemoteError, ProtocolRemoteError, VersionRemoteError {
ClientDownloadTCP downLoader = new ClientDownloadTCP(filename, hostList, partsSubdir, baseDirectory); ClientDownloadTCP downLoader = new ClientDownloadTCP(filename, hostList, partsSubdir, baseDirectory, logger);
Thread t = new Thread(downLoader); Thread t = new Thread(downLoader);
t.start(); t.start();
try { try {
@ -125,15 +144,18 @@ public class ClientManagementTCP implements Runnable {
byte[] hash512 = downLoader.getHashSum512(); byte[] hash512 = downLoader.getHashSum512();
if (!Arrays.equals(hash512, computeHashsum(filename, HashAlgorithm.SHA512))) { if (!Arrays.equals(hash512, computeHashsum(filename, HashAlgorithm.SHA512))) {
System.err.println("Error: Hashsum does not match"); System.err.println("Error: Hashsum does not match");
logger.writeTCP("Error: Hashsum does not match", LogLevel.Error);
System.err.println("Computed checksum:"); System.err.println("Computed checksum:");
byte[] c = computeHashsum(filename, HashAlgorithm.SHA512); byte[] c = computeHashsum(filename, HashAlgorithm.SHA512);
for (byte b: c) { for (byte b: c) {
System.err.print(String.format("%02X", b)); System.err.print(String.format("%02X", b));
logger.writeTCP("Computed checksum:" + String.format("%02X", b), LogLevel.Info);
} }
System.err.println(""); System.err.println("");
System.err.println("Received checksum:"); System.err.println("Received checksum:");
for (byte b: hash512) { for (byte b: hash512) {
System.err.print(String.format("%02X", b)); System.err.print(String.format("%02X", b));
logger.writeTCP("Received checksum:" + String.format("%02X", b), LogLevel.Info);
} }
System.err.println(""); System.err.println("");
throw new InternalError(); throw new InternalError();
@ -172,11 +194,14 @@ public class ClientManagementTCP implements Runnable {
return ((FileList)p).getFileList(); return ((FileList)p).getFileList();
} }
} catch (NotFound e) { } catch (NotFound e) {
logger.writeTCP(e, LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} catch (EmptyFile e) { } catch (EmptyFile e) {
logger.writeTCP(e, LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} catch (SocketClosed e){ } catch (SocketClosed e){
System.err.println("listDirectory : SocketClosed"); System.err.println("listDirectory : SocketClosed");
logger.writeTCP("listDirectory : SocketClosed", LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} }
} }
@ -191,8 +216,10 @@ public class ClientManagementTCP implements Runnable {
return md.digest(Files.readAllBytes(Paths.get(baseDirectory + filename))); return md.digest(Files.readAllBytes(Paths.get(baseDirectory + filename)));
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
System.out.println("Error: " + h.getName() + " not supported"); System.out.println("Error: " + h.getName() + " not supported");
logger.writeTCP("Error: " + h.getName() + " not supported", LogLevel.Error);
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error: cannot read " + filename); System.out.println("Error: cannot read " + filename);
logger.writeTCP("Error: cannot read " + filename, LogLevel.Error);
} }
return new byte[0]; return new byte[0];
} }

@ -1,4 +1,17 @@
package clientP2P; package clientP2P;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import java.io.File;
import java.net.DatagramSocket;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import localException.InternalError; import localException.InternalError;
import localException.ProtocolError; import localException.ProtocolError;
import localException.SizeError; import localException.SizeError;
@ -10,17 +23,6 @@ import remoteException.InternalRemoteError;
import remoteException.NotFound; import remoteException.NotFound;
import remoteException.ProtocolRemoteError; import remoteException.ProtocolRemoteError;
import remoteException.VersionRemoteError; import remoteException.VersionRemoteError;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.net.DatagramSocket;
import java.io.IOException;
import java.nio.file.Files;
import java.io.File;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import tools.HostItem;
import protocolP2P.ProtocolP2PPacketUDP; import protocolP2P.ProtocolP2PPacketUDP;
import protocolP2P.Payload; import protocolP2P.Payload;
import protocolP2P.RequestResponseCode; import protocolP2P.RequestResponseCode;
@ -30,8 +32,9 @@ import protocolP2P.LoadRequest;
import protocolP2P.HashAlgorithm; import protocolP2P.HashAlgorithm;
import protocolP2P.HashRequest; import protocolP2P.HashRequest;
import protocolP2P.HashResponse; import protocolP2P.HashResponse;
import java.security.MessageDigest; import tools.HostItem;
import java.security.NoSuchAlgorithmException; import tools.Logger;
import tools.LogLevel;
import clientP2P.ClientDownloadUDP; import clientP2P.ClientDownloadUDP;
/** Implementation of P2P-JAVA-PROJECT CLIENT /** Implementation of P2P-JAVA-PROJECT CLIENT
@ -44,16 +47,18 @@ public class ClientManagementUDP implements Runnable {
private String baseDirectory; private String baseDirectory;
private String partsSubdir; private String partsSubdir;
private List<HostItem> hostList; private List<HostItem> hostList;
private Logger logger;
/** Constructor for UDP implementation, with baseDirectory and UDPPort parameters. /** Constructor for UDP implementation, with baseDirectory and UDPPort parameters.
* @param baseDirectory the root directory where files are stored * @param baseDirectory the root directory where files are stored
* @param host hostname of the server * @param host hostname of the server
* @param UDPPort the server will listen on this port * @param UDPPort the server will listen on this port
*/ */
public ClientManagementUDP(String baseDirectory, List<HostItem> hostList, String partsSubdir) { public ClientManagementUDP(String baseDirectory, List<HostItem> hostList, String partsSubdir, Logger logger) {
this.baseDirectory = baseDirectory; this.baseDirectory = baseDirectory;
this.hostList = hostList; this.hostList = hostList;
this.partsSubdir = partsSubdir; this.partsSubdir = partsSubdir;
this.logger = logger;
} }
/** Implementation of Runnable /** Implementation of Runnable
@ -70,33 +75,47 @@ public class ClientManagementUDP implements Runnable {
System.out.println("Name of the file to download:"); System.out.println("Name of the file to download:");
String f = scanner.nextLine(); String f = scanner.nextLine();
download(f); download(f);
System.out.println("File sucessfully downloaded"); System.out.println("File " + f + " sucessfully downloaded");
logger.writeUDP("File " + f + " sucessfully downloaded", LogLevel.Info);
} catch (EmptyDirectory e) { } catch (EmptyDirectory e) {
System.err.println("Error: Server has no file in directory"); System.err.println("Error: Server has no file in directory");
logger.writeUDP("Error: Server has no file in directory", LogLevel.Error);
} catch (InternalError e) { } catch (InternalError e) {
System.err.println("Error: Client internal error"); System.err.println("Error: Client internal error");
logger.writeUDP("Error: Client internal error", LogLevel.Error);
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
System.err.println("Error: Server host is unknown"); System.err.println("Error: Server host is unknown");
logger.writeUDP("Error: Server host is unknown", LogLevel.Error);
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error: Request cannot be send or response cannot be received"); System.err.println("Error: Request cannot be send or response cannot be received");
logger.writeUDP("Error: Request cannot be send or response cannot be received", LogLevel.Error);
} catch (TransmissionError e) { } catch (TransmissionError e) {
System.err.println("Error: Message received is too big"); System.err.println("Error: Message received is too big");
logger.writeUDP("Error: Message received is too big", LogLevel.Error);
} catch (ProtocolError e) { } catch (ProtocolError e) {
System.err.println("Error: Cannot decode servers response"); System.err.println("Error: Cannot decode servers response");
logger.writeUDP("Error: Cannot decode servers response", LogLevel.Error);
} catch (VersionError e) { } catch (VersionError e) {
System.err.println("Error: Servers response use bad version of the protocol"); System.err.println("Error: Servers response use bad version of the protocol");
logger.writeUDP("Error: Servers response use bad version of the protocol", LogLevel.Error);
} catch (SizeError e) { } catch (SizeError e) {
System.err.println("Error: Cannot handle this packets because of internal representation limitations of numbers on the client"); System.err.println("Error: Cannot handle this packets because of internal representation limitations of numbers on the client");
logger.writeUDP("Error: Cannot handle this packets because of internal representation limitations of numbers on the client", LogLevel.Error);
} catch (InternalRemoteError e) { } catch (InternalRemoteError e) {
System.err.println("Error: Server internal error"); System.err.println("Error: Server internal error");
logger.writeUDP("Error: Server internal error", LogLevel.Error);
} catch (ProtocolRemoteError e) { } catch (ProtocolRemoteError e) {
System.err.println("Error: Server cannot decode clients request"); System.err.println("Error: Server cannot decode clients request");
logger.writeUDP("Error: Server cannot decode clients request", LogLevel.Error);
} catch (VersionRemoteError e) { } catch (VersionRemoteError e) {
System.err.println("Error: Server cannot decode this version of the protocol"); System.err.println("Error: Server cannot decode this version of the protocol");
logger.writeUDP("Error: Server cannot decode this version of the protocol", LogLevel.Error);
} catch (NotFound e) { } catch (NotFound e) {
System.err.println("Error: Server has not this file in directory"); System.err.println("Error: Server has not this file in directory");
logger.writeUDP("Error: Server has not this file in directory", LogLevel.Error);
} catch (EmptyFile e) { } catch (EmptyFile e) {
System.err.println("Error: File is empty"); System.err.println("Error: File is empty");
logger.writeUDP("Error: File is empty", LogLevel.Error);
} }
} }
@ -116,7 +135,7 @@ public class ClientManagementUDP implements Runnable {
* @throws EmptyFile * @throws EmptyFile
*/ */
private void download(String filename) throws EmptyFile, NotFound, InternalError, UnknownHostException, IOException, TransmissionError, ProtocolError, VersionError, SizeError, InternalRemoteError, ProtocolRemoteError, VersionRemoteError { private void download(String filename) throws EmptyFile, NotFound, InternalError, UnknownHostException, IOException, TransmissionError, ProtocolError, VersionError, SizeError, InternalRemoteError, ProtocolRemoteError, VersionRemoteError {
ClientDownloadUDP downLoader = new ClientDownloadUDP(filename, hostList, partsSubdir, baseDirectory); ClientDownloadUDP downLoader = new ClientDownloadUDP(filename, hostList, partsSubdir, baseDirectory, logger);
Thread t = new Thread(downLoader); Thread t = new Thread(downLoader);
t.start(); t.start();
try { try {
@ -129,11 +148,13 @@ public class ClientManagementUDP implements Runnable {
byte[] c = computeHashsum(filename, HashAlgorithm.SHA512); byte[] c = computeHashsum(filename, HashAlgorithm.SHA512);
for (byte b: c) { for (byte b: c) {
System.err.print(String.format("%02X", b)); System.err.print(String.format("%02X", b));
logger.writeUDP("Computed checksum:" + String.format("%02X", b), LogLevel.Info);
} }
System.err.println(""); System.err.println("");
System.err.println("Received checksum:"); System.err.println("Received checksum:");
for (byte b: hash512) { for (byte b: hash512) {
System.err.print(String.format("%02X", b)); System.err.print(String.format("%02X", b));
logger.writeUDP("Received checksum:" + String.format("%02X", b), LogLevel.Info);
} }
System.err.println(""); System.err.println("");
throw new InternalError(); throw new InternalError();
@ -142,6 +163,7 @@ public class ClientManagementUDP implements Runnable {
throw new InternalError(); throw new InternalError();
} }
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.writeUDP(e, LogLevel.Error);
throw new InternalError(); throw new InternalError();
} }
} }
@ -172,8 +194,10 @@ public class ClientManagementUDP implements Runnable {
return ((FileList)p).getFileList(); return ((FileList)p).getFileList();
} }
} catch (NotFound e) { } catch (NotFound e) {
logger.writeUDP(e, LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} catch (EmptyFile e) { } catch (EmptyFile e) {
logger.writeUDP(e, LogLevel.Error);
throw new ProtocolError(); throw new ProtocolError();
} }
} }
@ -188,8 +212,10 @@ public class ClientManagementUDP implements Runnable {
return md.digest(Files.readAllBytes(Paths.get(baseDirectory + filename))); return md.digest(Files.readAllBytes(Paths.get(baseDirectory + filename)));
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
System.out.println("Error: " + h.getName() + " not supported"); System.out.println("Error: " + h.getName() + " not supported");
logger.writeUDP("Error: " + h.getName() + " not supported", LogLevel.Error);
} catch (IOException e) { } catch (IOException e) {
System.out.println("Error: cannot read " + filename); System.out.println("Error: cannot read " + filename);
logger.writeUDP("Error: cannot read " + filename, LogLevel.Error);
} }
return new byte[0]; return new byte[0];
} }

@ -1,4 +1,7 @@
package clientP2P; package clientP2P;
import java.util.Scanner;
import java.util.List;
import clientP2P.ClientManagementUDP; import clientP2P.ClientManagementUDP;
import clientP2P.ClientManagementTCP; import clientP2P.ClientManagementTCP;
import serverP2P.ServerManagementUDP; import serverP2P.ServerManagementUDP;
@ -7,8 +10,6 @@ import tools.Directories;
import tools.Logger; import tools.Logger;
import tools.LogLevel; import tools.LogLevel;
import tools.Directories; import tools.Directories;
import java.util.Scanner;
import java.util.List;
import tools.HostItem; import tools.HostItem;
import tools.HostList; import tools.HostList;
@ -18,10 +19,12 @@ import tools.HostList;
* @author JS Auge * @author JS Auge
* @version 1.0 * @version 1.0
*/ */
public class ClientP2P { public class ClientP2P {
static private final String subdir = "seeded/"; static private final String subdir = "seeded/";
static private String parts = ".parts"; static private String parts = ".parts";
private Logger logger; private Logger loggerServer;
private Logger loggerClient;
private String host; private String host;
private int port; private int port;
private Directories directories; private Directories directories;
@ -29,13 +32,14 @@ public class ClientP2P {
private static final int defaultPort = 20000; private static final int defaultPort = 20000;
/** Initialize logger if directories and logger are null, /** Initialize loggers if directories and logger are null,
* else fail silently. * else fail silently.
*/ */
public void initLogger() { public void initLogger() {
if (directories == null && logger == null) { if (directories == null && loggerServer == null && loggerClient == null) {
directories = new Directories("P2P_JAVA_PROJECT" + port); directories = new Directories("P2P_JAVA_PROJECT_" + port);
logger = new Logger(directories.getDataHomeDirectory() + "server.log"); loggerServer = new Logger(directories.getDataHomeDirectory() + "server.log");
loggerClient = new Logger(directories.getDataHomeDirectory() + "client.log");
} }
} }
@ -50,7 +54,7 @@ public class ClientP2P {
port = defaultPort; port = defaultPort;
initLogger(); initLogger();
System.err.println("Error incorrect port " + oldPort + " using default port " + defaultPort); System.err.println("Error incorrect port " + oldPort + " using default port " + defaultPort);
logger.write("incorrect port " + oldPort + " using default port " + defaultPort, LogLevel.Info); loggerServer.write("incorrect port " + oldPort + " using default port " + defaultPort, LogLevel.Info);
} }
initLogger(); initLogger();
directories.createSubdir(subdir); directories.createSubdir(subdir);
@ -65,7 +69,7 @@ public class ClientP2P {
* 1rst parameter is optionnal, and is used to * 1rst parameter is optionnal, and is used to
* define port used by the server module to listen. If not provided, default to another port. * define port used by the server module to listen. If not provided, default to another port.
* @param args server listenning port * @param args server listenning port
*/ */
public static void main(String [] args) { public static void main(String [] args) {
ClientP2P c; ClientP2P c;
try { try {
@ -75,8 +79,8 @@ public class ClientP2P {
} }
// Server threads // Server threads
ServerManagementUDP smudp = new ServerManagementUDP(c.directories.getDataHomeDirectory() + subdir, c.port, c.logger); ServerManagementUDP smudp = new ServerManagementUDP(c.directories.getDataHomeDirectory() + subdir, c.port, c.loggerServer);
ServerManagementTCP smtcp = new ServerManagementTCP(c.directories.getDataHomeDirectory() + subdir, c.port, c.logger); ServerManagementTCP smtcp = new ServerManagementTCP(c.directories.getDataHomeDirectory() + subdir, c.port, c.loggerServer);
Thread tudp = new Thread(smudp); Thread tudp = new Thread(smudp);
tudp.setName("server UDP P2P-JAVA-PROJECT (port: " + c.port + ")"); tudp.setName("server UDP P2P-JAVA-PROJECT (port: " + c.port + ")");
tudp.start(); tudp.start();
@ -104,7 +108,7 @@ public class ClientP2P {
case "upd": // alias typo case "upd": // alias typo
case "2" : case "2" :
System.out.println("Starting with UDP"); System.out.println("Starting with UDP");
ClientManagementUDP cmudp = new ClientManagementUDP(c.directories.getDataHomeDirectory(), c.hostList, c.directories.getDataHomeDirectory() + c.parts + "/"); ClientManagementUDP cmudp = new ClientManagementUDP(c.directories.getDataHomeDirectory(), c.hostList, c.directories.getDataHomeDirectory() + c.parts + "/", c.loggerClient);
t = new Thread(cmudp); t = new Thread(cmudp);
break; break;
case "TCP": case "TCP":
@ -112,7 +116,7 @@ public class ClientP2P {
case "1": case "1":
default: default:
System.out.println("Starting with TCP"); System.out.println("Starting with TCP");
ClientManagementTCP cmtcp = new ClientManagementTCP(c.directories.getDataHomeDirectory(), c.hostList, c.directories.getDataHomeDirectory() + c.parts + "/"); ClientManagementTCP cmtcp = new ClientManagementTCP(c.directories.getDataHomeDirectory(), c.hostList, c.directories.getDataHomeDirectory() + c.parts + "/", c.loggerClient);
t = new Thread(cmtcp); t = new Thread(cmtcp);
break; break;
} }

Loading…
Cancel
Save