View Javadoc
1   /*
2    * Copyright (c) 2002-2017, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.deployment.util;
35  
36  import fr.paris.lutece.plugins.deployment.business.CommandResult;
37  import fr.paris.lutece.plugins.deployment.business.FtpInfo;
38  import fr.paris.lutece.portal.service.util.AppLogService;
39  
40  import org.apache.commons.net.ftp.FTP;
41  import org.apache.commons.net.ftp.FTPClient;
42  import org.apache.commons.net.ftp.FTPConnectionClosedException;
43  import org.apache.commons.net.ftp.FTPHTTPClient;
44  import org.apache.commons.net.ftp.FTPReply;
45  
46  import java.io.FileInputStream;
47  import java.io.FileNotFoundException;
48  import java.io.IOException;
49  import java.io.InputStream;
50  import java.io.OutputStream;
51  
52  public class FTPUtils
53  {
54  
55      public static String uploadFile( String fileName, InputStream inputStream, FtpInfo ftpInfo, String remoteDirectoryPath, CommandResult commandResult,
56              boolean bBinaryFile )
57      {
58          final FTPClient ftp = getFtpClient( ftpInfo );
59          String strRemoteFilePath = remoteDirectoryPath + ConstanteUtils.CONSTANTE_SEPARATOR_SLASH + fileName;
60  
61          if ( ftp != null )
62  
63          {
64              // login
65              try
66              {
67                  if ( !ftp.login( ftpInfo.getUserLogin( ), ftpInfo.getUserPassword( ) ) )
68                  {
69                      ftp.logout( );
70                      DeploymentUtils.addTechnicalError( commandResult, "Probleme de connexion FTP,le compte FTP n'est pas reconnu" + strRemoteFilePath );
71                  }
72  
73                  if ( bBinaryFile )
74                  {
75                      ftp.setFileType( FTP.BINARY_FILE_TYPE );
76                  }
77                  boolean bStorefile = ftp.storeFile( strRemoteFilePath, inputStream );
78  
79                  if ( !bStorefile )
80                  {
81                      // try again
82                      bStorefile = ftp.storeFile( strRemoteFilePath, inputStream );
83                  }
84  
85                  if ( !bStorefile )
86                  {
87                      DeploymentUtils.addTechnicalError( commandResult, "Probleme lors du dépot du fichier en FTP " + strRemoteFilePath );
88                  }
89  
90                  inputStream.close( );
91  
92                  ftp.noop( ); // check that control connection is working OK
93  
94                  ftp.logout( );
95              }
96  
97              catch( FTPConnectionClosedException e )
98              {
99                  DeploymentUtils.addTechnicalError( commandResult, "Une erreur est survenue lors de la fermeture de la connexion FTP:" + e.getMessage( )
100                         + strRemoteFilePath, e );
101             }
102             catch( IOException e )
103             {
104                 DeploymentUtils.addTechnicalError( commandResult, "Une erreur est survenue lors du transfert FTP" + e.getMessage( ) + strRemoteFilePath, e );
105             }
106             finally
107             {
108                 if ( ftp.isConnected( ) )
109                 {
110                     try
111                     {
112                         ftp.disconnect( );
113                     }
114                     catch( IOException f )
115                     {
116                         // do nothing
117                     }
118                 }
119             }
120         }
121         else
122         {
123             DeploymentUtils.addTechnicalError( commandResult, "Probleme de connexion FTP" + strRemoteFilePath );
124 
125         }
126 
127         // upload File
128         return null;
129     }
130 
131     public static String getFile( OutputStream outputStream, FtpInfo ftpInfo, String remoteFilePath, CommandResult commandResult )
132     {
133         final FTPClient ftp = getFtpClient( ftpInfo );
134 
135         if ( ftp != null )
136 
137         {
138 
139             // login
140             try
141             {
142                 if ( !ftp.login( ftpInfo.getUserLogin( ), ftpInfo.getUserPassword( ) ) )
143                 {
144                     DeploymentUtils.addTechnicalError( commandResult, "Probleme de connexion FTP,le compte FTP n'est pas reconnu" + remoteFilePath );
145 
146                     ftp.logout( );
147 
148                 }
149 
150                 boolean bRetrieve = ftp.retrieveFile( remoteFilePath, outputStream );
151 
152                 if ( !bRetrieve )
153                 {
154                     // Try Again
155                     bRetrieve = ftp.retrieveFile( remoteFilePath, outputStream );
156                 }
157 
158                 if ( !bRetrieve )
159                 {
160                     DeploymentUtils.addTechnicalError( commandResult, "Probleme lors de la récupération du fichier en FTP" + remoteFilePath );
161                 }
162 
163                 outputStream.flush( );
164                 // close output stream
165                 outputStream.close( );
166 
167                 ftp.noop( ); // check that control connection is working OK
168 
169                 ftp.logout( );
170             }
171 
172             catch( FTPConnectionClosedException e )
173             {
174                 DeploymentUtils.addTechnicalError( commandResult, "Une erreur est survenue lors de la fermeture de la connexion FTP:" + e.getMessage( )
175                         + remoteFilePath, e );
176 
177             }
178             catch( IOException e )
179             {
180                 DeploymentUtils.addTechnicalError( commandResult, "Une erreur est survenue lors du transfert FTP:" + e.getMessage( ) + remoteFilePath, e );
181 
182             }
183             finally
184             {
185                 if ( ftp.isConnected( ) )
186                 {
187                     try
188                     {
189                         ftp.disconnect( );
190                     }
191                     catch( IOException f )
192                     {
193                         // do nothing
194                     }
195                 }
196             }
197         }
198         else
199         {
200             DeploymentUtils.addTechnicalError( commandResult, "Probleme de connexion FTP" + remoteFilePath );
201 
202         }
203 
204         // upload File
205         return null;
206     }
207 
208     public static String uploadFile( String fileName, String pathLocalFile, FtpInfo ftpInfo, String remoteDirectoryPath, CommandResult commandResult,
209             boolean bBinaryFile )
210     {
211         final FTPClient ftp = getFtpClient( ftpInfo );
212 
213         // login
214 
215         InputStream input = null;
216 
217         try
218         {
219             input = new FileInputStream( pathLocalFile );
220         }
221         catch( FileNotFoundException e )
222         {
223             // TODO Auto-generated catch block
224             DeploymentUtils.addTechnicalError( commandResult, "Une erreur est survenue lors de l'upload du fichier" + pathLocalFile + ":" + e.getMessage( ), e );
225 
226         }
227 
228         return uploadFile( fileName, input, ftpInfo, remoteDirectoryPath, commandResult, bBinaryFile );
229 
230     }
231 
232     private static FTPClient getFtpClient( FtpInfo ftpInfo )
233     {
234         final FTPClient ftp;
235 
236         if ( ftpInfo.getProxyHost( ) != null )
237         {
238             ftp = new FTPHTTPClient( ftpInfo.getProxyHost( ), ftpInfo.getProxyPort( ), ftpInfo.getProxyUserLogin( ), ftpInfo.getProxyUserPassword( ) );
239         }
240         else
241         {
242             ftp = new FTPClient( );
243         }
244 
245         // add keepAlive
246         if ( ftpInfo.getKeepAliveTimeout( ) >= 0 )
247         {
248             ftp.setControlKeepAliveTimeout( ftpInfo.getKeepAliveTimeout( ) );
249         }
250 
251         try
252         {
253             int reply;
254 
255             if ( ftpInfo.getPort( ) > 0 )
256             {
257                 ftp.connect( ftpInfo.getHost( ), ftpInfo.getPort( ) );
258             }
259             else
260             {
261                 ftp.connect( ftpInfo.getHost( ) );
262             }
263 
264             AppLogService.debug( "Connected to " + ftpInfo.getHost( ) + " on " + ( ( ftpInfo.getPort( ) > 0 ) ? ftpInfo.getPort( ) : ftp.getDefaultPort( ) ) );
265 
266             // After connection attempt, you should check the reply code to
267             // verify
268             // success
269             reply = ftp.getReplyCode( );
270 
271             if ( !FTPReply.isPositiveCompletion( reply ) )
272             {
273                 ftp.disconnect( );
274                 AppLogService.error( "FTP server refused connection." );
275 
276             }
277 
278             return ftp;
279         }
280         catch( IOException e )
281         {
282             if ( ftp.isConnected( ) )
283             {
284                 try
285                 {
286                     ftp.disconnect( );
287                 }
288                 catch( IOException f )
289                 {
290                     // do nothing
291                 }
292             }
293 
294             AppLogService.error( "Could not connect to server." + e, e );
295 
296         }
297 
298         return null;
299     }
300 }