You are on page 1of 8

package sdown.Telechargement.

TelFTP;
/*******************************************************************************
* Ce Code est une partie de l'application SuperDownloader - Utilitaire **
*** de Télechargement FTP et HTTP,inspiré de plusieurs Codes Sources. **
****** Copyright (c) 2005 KARAMI Mohamed & BOUSSOUF Ali **
******** **
*********** Ce Programme est un Soft Gratuit; Vous pouvez le redistribuer **
************** et/ou le modifier sous les Termes de General Public **
**************** License "GNU". **
****************** Ce programme est distribué dans le but d'ètre util, **
********************* mais SANS AUCUNE GARANTIE; Consulter la Licence **
************************ GNU General Public pous plus de Détails. **
*************************** **
****************************** Pour Vos Remarques : ens_soft@yahoo.fr **
******************************************************************************/
import sdown.Telechargement.*;
import sdown.Telechargement.downloadGUI.*;
import sdown.Historique.*;
import sdown.ParamProjet.*;
import sdown.Utilitaires.MsgDown.*;
import javax.swing.*;
import java.net.URL;
import sun.net.www.protocol.ftp.FtpURLConnection;
import java.io.*;
import java.util.Calendar;
import javax.sound.midi.*;
import java.awt.Color;
/**
* Classe télechargement FTP
* @author KARAMI Mohamed & BOUSSOUF Ali
* @version 2.02
*/
public class DownFTP {
private String urlName;
private String location;
private String slash = System.getProperties().getProperty("file.separator");
private boolean downloadSuccess;
private JProgressBar progress;
private String saveFileTo, tempFile, propertiesFile, nameOfFile,BUFFER_SIZE,
tempDirectory;
private URL urlToDownload;
private InputStream input;
private BufferedWriter props;
private JTextField statusField;
private DownControl downloadControl;
NewDown newDownload;
/** Constructeur de classe
* @param downloadControl Instance de "downloadcontrol"
* @param urlName l'url à télecharger
* @param location location d'enregistrement du fichier
* @param progress la barre de progression
* @param statusField barre d'etat pour les msg
* @param newDownload Instance de newdownload
*/
public DownFTP(DownControl downloadControl, String urlName, String location,
JProgressBar progress, JTextField statusField, NewDown newDownload) {
this.urlName = urlName;
this.location = location;
this.progress = downloadControl.getProgressBar();
this.statusField = downloadControl.getNewDownloadStatus();
this.downloadControl = downloadControl;
this.newDownload = newDownload;
}
/** demarrer le télechargement
* @return succés du télechargement
*/
public boolean startDownload() {
try {
downloadControl.getNewDownloadStatus().setText("Configuration du Pro
xy");
Traces.aNewMessage("Etat du Télechargement", "Configuration du Proxy")
;
ParamProxy.setProxy();
downloadControl.getNewDownloadStatus().setText("Proxy Configuré");
Traces.aNewMessage("Etat du Télechargement", "Proxy Configuré");
int totalSize;
BUFFER_SIZE = ParamValeurs.getPropertyValue("BUFFER_SIZE");
tempDirectory = ParamValeurs.getPropertyValue("TEMP");
progress.setStringPainted(false);
if (urlName == null || location.length() <= 0) {
newDownload.resetButtons();
return false;
}
urlToDownload = new URL(urlName);
int index = urlName.lastIndexOf("/") + 1;
if (index != -1)
nameOfFile = urlName.substring(index, urlName.length());
else
nameOfFile = urlName;
this.saveFileTo = location;
if (urlToDownload == null) {
newDownload.resetButtons();
return false;
} else {
FtpURLConnection connection = openConnFtp();
if (connection != null) {
totalSize = connection.getContentLength();
downloadSuccess = downloadFile(connection, totalSize, nameOf
File);
if (downloadSuccess && !downloadControl.getApplicationStopSt
atus()) {
downloadSuccess = renameTempFile(nameOfFile, tempFile);
if (downloadSuccess && !downloadControl.getApplicationSt
opStatus())
downloadSuccess = deletePropFileOnCompletion(propert
iesFile);
if (downloadSuccess) {
newDownload.resetButtons();
return downloadSuccess;
}
}
} else {
newDownload.resetButtons();
return false;
}
}
return false;
} catch (Exception e) {
if (e instanceof java.net.MalformedURLException)
new MsgDialog("l'URL spécifié n'est pas valide, veuillez la véréfier SVP
");
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return false;
}
}
/** supprime le fichier temporaire
* @param propertiesFile proprietés du fichier
* @return succés du télechargement
*/
private boolean deletePropFileOnCompletion(String propertiesFile) {
try {
Traces.aNewMessage("Etat du Télechargement", "Suppression des ancienne
s propriétès du fichier");
System.gc();
if (propertiesFile != null)
return new File(propertiesFile).delete();
else
return false;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return false;
}
}
/**
* renommer le fichier temporaire en fichier reel
* @param file le nom du fichier sur disque
* @param temp1 fichier temporaire à renommer
* @return succés du renommage du fichier
*/
private boolean renameTempFile(String file, String temp1) {
try {
Traces.aNewMessage("Etat du Télechargement", "Rennomage du fichier tem
poraire au fichier actuel");
System.gc();
File tempFile = new File(temp1);
if (tempFile.exists()) {
String fileName = saveFileTo + file.substring(0, file.length());
File f2 = new File(fileName);
if (f2.exists()) {
boolean delete = f2.delete();
if (!delete) {
statusField.setText("Impossible de supprimer le fichier
dans '" + fileName + "' Supprimer le manuelement");
Traces.aNewMessage("Etat du Télechargement", "Impossible d
e supprimer le fichier dans '" + fileName + "' Supprimer le manuelement");
}
}
return tempFile.renameTo(f2);
} else
return false;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return false;
}
}
/**
* ouvrir la connexion avec l'url à télecharger
* @return la connexion FtpURLConnection
*/
private FtpURLConnection openConnFtp() {
try {
FtpURLConnection connection = (FtpURLConnection) urlToDownload.openC
onnection();
statusField.setText("Connexion à l'URL " + urlToDownload);
Traces.aNewMessage("Etat du Télechargement", "Connexion à l'URL " + urlT
oDownload);
if (connection == null)
return null;
//statusField.setText("code serveur " + connection.getResponseCode()
);
//Traces.aNewMessage("Etat du Télechargement", "Code serveur " + conne
ction.getResponseCode());
connection.connect();
//connection.setConnectTimeout(600); sous JDK5
//System.out.println("temps de conftp :"+connection.getConnectTimeou
t());
statusField.setText("Connexion réussite à l'URL, Ouverture de l'URL...")
;
Traces.aNewMessage("Etat du Télechargement", "Connexion réussite à l'URL,
Ouverture de l'URL...");
input = connection.getInputStream();
statusField.setText("Taille du Fichier " + connection.getContentLeng
th());
Traces.aNewMessage("Etat du Télechargement", "Taille du Fichier " + co
nnection.getContentLength());
return connection;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return null;
}
}
/**
* generer une clé securisée pour le fichier
* @param fileLength taille du fichier à integrer dans la clé
* @return la clé
*/
private String getUniqueNum(int fileLength) {
try {
Calendar cal = Calendar.getInstance();
int num1 = cal.get(Calendar.MILLISECOND);
int num2 = cal.get(Calendar.YEAR);
int num3 = cal.get(Calendar.MONTH);
int num4 = cal.get(Calendar.DAY_OF_WEEK);
int num5 = cal.get(Calendar.YEAR);
int num6 = cal.get(Calendar.HOUR_OF_DAY);
int num7 = cal.get(Calendar.MINUTE);
int num8 = cal.get(Calendar.SECOND);
String secureNum = num8 + num7 + num1 + fileLength + num1 + num8 + n
um8 + num2 + num1 + num3 + num4 + num5 + num1 + num6 +
"0" + fileLength + (num2 * 1) + num7 + fileLength + num7;
return secureNum;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return null;
}
}
/**
* Télecharger après l'ouverture de la connexion
*
* @param connection la connexion FtpURLConnection
* @param totalSize taille du fichier
* @param nameOfFile nom du fichier
* @return succés du télechargement
*/
private synchronized boolean downloadFile(FtpURLConnection connection, int t
otalSize, String nameOfFile) {
try {
statusField.setText("Lancement du Télechargement");
Traces.aNewMessage("Etat du Télechargement", "Lancement du Télechargemen
t");
boolean success = false;
byte[] abyte0;
long startTime = System.currentTimeMillis();
int j,counter = 0;
String secureNum = getUniqueNum(nameOfFile.length());
System.gc();
if (BUFFER_SIZE != null && BUFFER_SIZE.trim().length() > 1) {
abyte0 = new byte[Integer.parseInt(BUFFER_SIZE)];
} else {
abyte0 = new byte[4096];
}
tempFile = tempDirectory + slash + nameOfFile + "!" + secureNum + "R
";
propertiesFile = tempDirectory + slash + "prop!" + secureNum + "$";
BufferedInputStream inputs = new BufferedInputStream(input);
FileOutputStream out = new FileOutputStream(tempFile);
props = new BufferedWriter(new FileWriter(propertiesFile));
props.write(nameOfFile);
props.newLine();
props.write("Taille:" + connection.getContentLength());
props.newLine();
props.write(urlToDownload.toString());
props.newLine();
boolean finished = false;
String fait="lus ";
if (totalSize<1) fait="ouvert à ce stade ";
else progress.setVisible(true);
while (((j = inputs.read(abyte0)) != -1) && !downloadControl.getAppl
icationStopStatus()) {
while (downloadControl.getPauseStatus()) {
Thread.sleep(1000);
}
counter += j;
String message = "";

if (counter <= 1024) {


message = fait + counter + " b";
} else if (counter >= 1025 && counter < 1025000) {
double theSize = ((double) counter / 1024D);
String temp = String.valueOf(theSize);
int index2 = temp.lastIndexOf(".");
if (index2 != -1)
temp = temp.substring(0, index2);
message = fait + temp + " kb";
} else if (counter >= 1025001) {
double theSize = ((double) counter / 1024D);
theSize = theSize / 1024D;
String temp = String.valueOf(theSize);
int index2 = temp.lastIndexOf(".");
if (index2 == -1)
index2 = temp.length();
if ((index2 + 3) <= temp.length()) {
temp = temp.substring(0, (index2 + 3));
} else if ((index2 + 2) <= temp.length()) {
temp = temp.substring(0, (index2 + 2));
} else {
temp = temp.substring(0, (index2 + 1));
}
message = fait + temp + " mb";
}
statusField.setText(message);
double done = ((double) counter / totalSize);
done *= 100D;
setProgressBar(done);
out.write(abyte0, 0, j);
writeCounter(counter);
finished = true;
}
if ((!downloadControl.getApplicationStopStatus()) && (!downloadContr
ol.getPauseStatus())) {
long end = System.currentTimeMillis();
long timeTaken = end - startTime;
long kb = 0;
timeTaken = (timeTaken / 1000);
if (timeTaken != 0)
kb = ((counter / 1027) / timeTaken);
else
kb = ((counter / 1027));
statusField.setText("Télechargement Terminé");
Traces.aNewMessage("Etat de Télechargement", "Télechargement Terminé")
;
newDownload.resetButtons();
new MsgFin(urlToDownload, saveFileTo + nameOfFile, timeTaken, kb
, newDownload, counter);
}
props.flush();
props.close();
out.flush();
out.close();
input.close();
return true;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return false;
}
}
/**
* ecrit le compteur dans le fichier temp
* @param counter compteur
* @return succés d'ecriture
*/
private boolean writeCounter(int counter) {
try {
props.write("-" + String.valueOf(counter));
props.flush();
return true;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return false;
}
}
/** MAJ de la barre de progression
* @param value valeur de la barre de progression
* @return succés de MAJ
*/
private boolean setProgressBar(double value) {
try {
//progress.resize(200,10);
String val = String.valueOf(value);
int index = (val.lastIndexOf("."));
if (index != -1)
val = val.substring(0, index);
if (val != null)
progress.setValue(Integer.parseInt(val));
return true;
} catch (Exception e) {
new MsgErreur(this.getClass().getName(),000,e,e.getLocalizedMessage(
));
newDownload.resetButtons();
return false;
}
}
}

You might also like