Forum |  HardWare.fr | News | Articles | PC | S'identifier | S'inscrire | Shop Recherche
1479 connectés 

  FORUM HardWare.fr
  Programmation
  Java

  JAVA Ftp Quartz

 


 Mot :   Pseudo :  
 
Bas de page
Auteur Sujet :

JAVA Ftp Quartz

n°2305483
killkala
Posté le 08-09-2017 à 12:20:43  profilanswer
 

Bonjour,  
 
Je me permet de poster car j'ai un soucis et peut-être que vous pourrez m'aider !  
Pour un projet, on m'a demander d'établir une connection FTP en Java afin de download des fichiers (Pour cela il n'y a pas de problème). On m'a demandé que le programme récupère toutes les heures fichiers (car ils subiront une modification régulière). J'ai donc pour cela décié d'utiliser Quartz et plus particulièrement Cron Schedule.  
Le problème est donc le tout ensemble. Je vous montre mon code pour que vous puissiez voir (je pense que j'utilise mal mon Job mais comme je ne connais pas du tout cette API j'ai du mal à comprendre)  
 
Quartz.java  
 

Code :
  1. package com.auscult.ftp;
  2. import java.io.IOException;
  3. import java.util.TimeZone;
  4. import org.quartz.CronScheduleBuilder;
  5. import org.quartz.JobBuilder;
  6. import org.quartz.JobDetail;
  7. import org.quartz.Scheduler;
  8. import org.quartz.SchedulerException;
  9. import org.quartz.SchedulerFactory;
  10. import org.quartz.Trigger;
  11. import org.quartz.TriggerBuilder;
  12. import org.quartz.impl.StdSchedulerFactory;
  13. public class Quartz {
  14.  public static void main(final String[] args) {
  15.      final SchedulerFactory factory = new StdSchedulerFactory();
  16.      Scheduler scheduler = null;
  17.      try {
  18.        scheduler = factory.getScheduler();
  19.        final JobDetail jobDetail = JobBuilder
  20.            .newJob(FTPFunctions.class)
  21.            .withIdentity("monJob", "groupe_1" )
  22.            .usingJobData("monParametre", "12345" )
  23.            .build();
  24.        final Trigger cronTrigger = TriggerBuilder
  25.            .newTrigger()
  26.            .withIdentity("monTrigger", "groupe_1" )
  27.            .withSchedule(
  28.                CronScheduleBuilder.cronSchedule("0 0/1 * * * ?" ) //Interval de 1mn afin de faire des test)
  29.                  .inTimeZone(TimeZone.getTimeZone("Europe/Paris" )))
  30.            .build();
  31.        scheduler.start();
  32.        scheduler.scheduleJob(jobDetail, cronTrigger);
  33.        System.in.read();
  34.        if (scheduler != null) {
  35.          scheduler.shutdown();
  36.        }
  37.      } catch (final SchedulerException e) {
  38.        e.printStackTrace();
  39.      } catch (final IOException e) {
  40.        e.printStackTrace();
  41.      }
  42.    }
  43. }


 
FTPFunctions.java
 

Code :
  1. package com.auscult.ftp;
  2. import java.io.BufferedOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.io.PrintWriter;
  8. import org.apache.commons.net.PrintCommandListener;
  9. import org.apache.commons.net.ftp.FTP;
  10. import org.apache.commons.net.ftp.FTPClient;
  11. import org.apache.commons.net.ftp.FTPFile;
  12. import org.apache.commons.net.ftp.FTPReply;
  13. import org.quartz.Job;
  14. import org.quartz.JobExecutionContext;
  15. import org.quartz.JobExecutionException;
  16. public class FTPFunctions implements Job {
  17. private String host;
  18. private String username;
  19. private String password;
  20. private int port;
  21. private static String remoteFilePath;
  22. private static String savePath;
  23. private static String parentDir;
  24. private static String currentDir;
  25. private static String saveDir;
  26. private static FTPClient ftpClient = new FTPClient();
  27.  public FTPFunctions(String server, int pPort, String pUsername, String pPassword) throws Exception {
  28.   host = server;
  29.   port = pPort;
  30.   username = pUsername;
  31.   password = pPassword;
  32.   ftpClient.addProtocolCommandListener (new PrintCommandListener(new PrintWriter(System.out)));
  33.         int reply;
  34.         ftpClient.connect( host , port);
  35.         System.out.println("FTP URL is:"+ftpClient.getDefaultPort());
  36.         reply = ftpClient.getReplyCode();
  37.         if (!FTPReply.isPositiveCompletion(reply)) {
  38.             ftpClient.disconnect();
  39.             throw new Exception("Exception in connecting to FTP Server" );
  40.         }
  41.         ftpClient.login(username, password);
  42.         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  43.         ftpClient.enterLocalPassiveMode();     
  44.        
  45.  }
  46.  public static boolean downloadFTPFile(FTPClient ftpClient, String RemoteFilePath, String SavePath) throws IOException {
  47.   remoteFilePath  = RemoteFilePath;
  48.   savePath    = SavePath;
  49.   File downloadFile = new File(savePath);
  50.     
  51.      File parentDir = downloadFile.getParentFile();
  52.      if (!parentDir.exists()) {
  53.          parentDir.mkdir();
  54.      }
  55.         
  56.      OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));
  57.     
  58.      try {
  59.     
  60.          ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
  61.          return ftpClient.retrieveFile(remoteFilePath, outputStream);
  62.      } catch (IOException ex) {
  63.          throw ex;
  64.      } finally {
  65.          if (outputStream != null) {
  66.              outputStream.close();
  67.          }
  68.      }
  69.     }
  70.  public static void downloadDirectory(FTPClient ftpClient, String ParentDir, String CurrentDir, String SaveDir) throws IOException {
  71.   parentDir  = ParentDir;
  72.   currentDir = CurrentDir;
  73.   saveDir    = SaveDir;
  74.      String dirToList = parentDir;
  75.      if (!currentDir.equals("" )) {
  76.          dirToList += "/" + currentDir;
  77.      }
  78.      FTPFile[] subFiles = ftpClient.listFiles(dirToList);
  79.      if (subFiles != null && subFiles.length > 0) {
  80.          for (FTPFile aFile : subFiles) {
  81.              String currentFileName = aFile.getName();
  82.              if (currentFileName.equals("." ) || currentFileName.equals(".." )) {
  83.                  continue;
  84.              }
  85.              String filePath = parentDir + "/" + currentDir + "/"
  86.                      + currentFileName;
  87.              if (currentDir.equals("" )) {
  88.                  filePath = parentDir + "/" + currentFileName;
  89.              }
  90.              String newDirPath = saveDir + parentDir + File.separator + currentDir + File.separator + currentFileName;
  91.              if (currentDir.equals("" )) {
  92.                  newDirPath = saveDir + parentDir + File.separator
  93.                            + currentFileName;
  94.              }
  95.              if (aFile.isDirectory()) {
  96.                  File newDir = new File(newDirPath);
  97.                  boolean created = newDir.mkdirs();
  98.                  if (created) {
  99.                      System.out.println("CREATED the directory: " + newDirPath);
  100.                  } else {
  101.                      System.out.println("COULD NOT create the directory: " + newDirPath);
  102.                  }
  103.                  downloadDirectory(ftpClient, dirToList, currentFileName, saveDir);
  104.              } else {
  105.                  boolean success = downloadFTPFile(ftpClient, filePath, newDirPath);
  106.                  if (success) {
  107.                      System.out.println("DOWNLOADED the file: " + filePath);
  108.                  } else {
  109.                      System.out.println("COULD NOT download the file: " + filePath);
  110.                  }
  111.              }
  112.          }
  113.      }
  114.  }
  115.  public void disconnect(){
  116.         if (FTPFunctions.ftpClient.isConnected()) {
  117.              try {
  118.                  FTPFunctions.ftpClient.logout();
  119.                  FTPFunctions.ftpClient.disconnect();
  120.              } catch (IOException f) {
  121.              }
  122.          }
  123.     }
  124. public void execute(JobExecutionContext arg0) throws JobExecutionException {
  125.                 System.out.println("FTP execut" );
  126.   try {
  127.    FTPFunctions ftp = new FTPFunctions("Test", 21, "killkala", "test" );
  128.    String remoteDirPath = "/Station1";
  129.             String saveDirPath = "//192.168.7.191/web/FTP";
  130.  
  131.             FTPFunctions.downloadDirectory(ftpClient, remoteDirPath, "", saveDirPath);
  132.    System.out.println("FTP File downloaded successfully" );
  133.    ftp.disconnect();
  134.     } catch (Exception e) {
  135.      e.printStackTrace();
  136.     }       
  137. }
  138. }


 
Je pense que mon Job n'aime pas trop toutes mes fonctions privées & public plus haut. En faite le problème c'est que je n'ai aucune erreur, juste rien ne se passe dans ma console. J'ai fais des test dépendant pour essayer de comprendre et c'est pour cela que j'en suis arrivé à la conclusion que l'association de mon Job à ma classe FTPFunctions n'a pas été concluante !  
Je pense que ca dois être une erreur trop bete, mais j'ai pas encore assez de connaissances pour savoir !
Donc si jamais vous avez un peu de temps pour m'aider, ca serai avec grand plaisir !!!  
 
Merci d'avance pour vos réponses !

mood
Publicité
Posté le 08-09-2017 à 12:20:43  profilanswer
 

n°2305585
killkala
Posté le 12-09-2017 à 13:37:07  profilanswer
 

J'ai finalement résolu mes soucis.
Pour ceux que ça intéresse j'ai :  
- fais un handler de Job à part.  
- enlevé tous mes "statics" et supprimé ftpClient des paramètres de méthode
- rendu ma classe FTPFonctions AutoCloseable
- rendu paramétrable mon Job.  
 
Si certains on un soucis similaire qu'il n'hésite pas à consulter ce topic :  
 
https://www.developpez.net/forums/d [...] ost9606343
Mon code modifier y est posté dessus  


Aller à :
Ajouter une réponse
  FORUM HardWare.fr
  Programmation
  Java

  JAVA Ftp Quartz

 

Sujets relatifs
Problème Main en java avec XML eclipsegestion des collisions dans jeu en 2D java
Mon premier dev java sous AndroidCopie et suppression dossier FTP tout les jours
interface en java[Java] Erreur java.net.SocketException : socket closed (EOS)
Problème de paramètres Java en SQLJ (JDBC)JAVA, je bloque totalement...
Ouvrir un fichier sur java's Cool 4[Java] Erreur Compilation
Plus de sujets relatifs à : JAVA Ftp Quartz


Copyright © 1997-2022 Hardware.fr SARL (Signaler un contenu illicite / Données personnelles) / Groupe LDLC / Shop HFR