source: ether_core/trunk/kit/interactifKit/zipContent/src/AtaRemoteFileServer.java @ 6

Last change on this file since 6 was 6, checked in by cbipsl, 18 years ago

ajout rep ether

  • Property svn:executable set to *
File size: 19.0 KB
Line 
1package fr.alcatel.ether.app.common;
2
3// JDK - rmi
4import java.rmi.*;
5import java.rmi.server.*;
6// JDK - io
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileOutputStream;
10import java.io.BufferedOutputStream;
11import java.io.IOException;
12import java.io.FileNotFoundException;
13import java.net.MalformedURLException;
14// JDK - collections
15import java.util.ArrayList;
16import java.util.Map;
17import java.util.Collections;
18import java.util.HashMap;
19// Utilities
20import flafi.util.FileCopy2;
21import fr.alcatel.ether.app.common.Config;
22//import fr.alcatel.ether.app.order.Order;
23import fr.alcatel.ether.tools.Trace;
24
25public class AtaRemoteFileServer extends UnicastRemoteObject implements RemoteFileManager {
26                // Debugging
27                private static final boolean DEBUG = true;
28               
29                /** delegate to runnable queeuing server */
30                private QueuedFileServer server = null;
31               
32                /** Default buffer size used for copying */
33                public static final int DEFAULT_BUFFER_SIZE = 8192;
34                /** Default buffer size used for copying */
35                public static final int MIN_BUFFER_SIZE                 =  128;
36               
37                /** Current buffer size used for copying */
38                private int bufferSize = DEFAULT_BUFFER_SIZE;
39                /** Buffer used for copying */
40                private byte[] buffer;
41
42                transient RmiFileInputStream input = null;
43                private transient final Map inputs = Collections.synchronizedMap( new HashMap() );
44                private transient final Map inputBuffers = Collections.synchronizedMap( new HashMap() );
45               
46        /**
47         * Construire un RemoteFileServer résidant sur un hôte.
48         *
49         */
50    public AtaRemoteFileServer( ) throws RemoteException {
51        super();
52        Config.getConfig( );
53        Trace.getTrace( IF_REMOTE_FILE_MANAGER );
54        server = new QueuedFileServer( this );
55        Trace.debug(this,"AtaRemoteFileServer constructed");
56    }
57
58        /**
59         *      Modifier la taille du buffer utilisé pour lire et écrire des fichiers.
60         *      Valeurs négatives sont ignorées.
61         *
62         *      @param  bufferSize:     la taille du buffer en octets
63         */
64    public void setBufferSize( int bufferSize ) throws RemoteException {
65        if ( bufferSize >= MIN_BUFFER_SIZE ) {
66                this.bufferSize = bufferSize;
67        }
68    }
69
70        /**
71         *      Ouvrir un fichier distant pour lecture ou écriture.
72         *
73         *      @param  f:      le fichier distant
74         */
75    public void open( RemoteFile f ) throws RemoteException, IOException, FileNotFoundException {
76        /*
77        if ( DEBUG ) { Trace.debug( this, "Illegal call to AtaRemoteFileServer.open()" ); }
78        if ( DEBUG ) { System.out.println( "Illegal call to AtaRemoteFileServer.open()" ); }
79                        */
80         
81        File file = f.getFile( );
82        if ( DEBUG) Trace.debug( this, "Opening remote file " + file );
83        RmiFileInputStream input = (RmiFileInputStream)inputs.get( file );
84        if ( input != null ) {
85                throw new IOException( file + " is already open" );
86        }
87        FileInputStream in = new FileInputStream( file );
88        input = new RmiFileInputStream( in );
89        inputs.put( file, input );
90        inputBuffers.put( input, new byte[bufferSize] );
91   
92    }
93
94        /**
95         *      Fermer un fichier distant après lecture ou écriture.
96         *
97         *      @param  f:      le fichier distant
98         */
99    public void close( RemoteFile f ) throws RemoteException, IOException {
100        /*
101        if ( DEBUG ) { Trace.debug( this, "Illegal call to AtaRemoteFileServer.close()" ); }
102        if ( DEBUG ) { System.out.println( "Illegal call to AtaRemoteFileServer.close()" ); }
103                        */
104         
105        RmiFileInputStream input = (RmiFileInputStream)inputs.remove( f.getFile() );
106        if ( input != null ) {
107        if ( DEBUG) Trace.debug( this, "Closing remote file " + f.getFile() );
108                inputBuffers.remove( input );
109                input.close( );
110                }
111        else { 
112                throw new IOException( "No input stream to close" );
113        }
114   
115    }
116
117        /**
118         *      Lire un fichier distant.
119         *
120         *      @param  f:      le fichier distant
121         */
122    public byte[] read( RemoteFile f ) throws RemoteException, IOException {
123        /*
124        if ( DEBUG ) { Trace.debug( this, "Illegal call to AtaRemoteFileServer.read()" ); }
125        if ( DEBUG ) { System.out.println( "Illegal call to AtaRemoteFileServer.read()" ); }
126        return null;
127        */
128        if ( DEBUG ) { Trace.debug( this, "BEGINNING READ OF FILE:" + f);}
129        File file = f.getFile( );
130        RmiFileInputStream input = (RmiFileInputStream)inputs.get( file );
131        if ( input != null ) {
132                byte[] buffer = (byte[])inputBuffers.get( input );
133                int len = input.read( buffer );
134                if ( len > 0 ) {
135                        byte[] buf = new byte[len];
136                        for ( int i = 0; i < len; i++ ) {
137                                buf[i] = buffer[i];
138                        }
139                        if ( DEBUG ) { Trace.debug( this, "ENDING READ OF FILE:" + f); }
140                        return buf;
141                }
142                else {
143                        throw new IOException( "EOF reached" );
144                }
145        }
146        else {
147                if ( DEBUG ) { Trace.debug( this, "No input stream for " + file ); }
148                return new byte[0];
149        }
150    }
151   
152        /**
153         *      <p>Copier un fichier distant.</p>
154         *
155         *      @param  src:    le fichier source
156         *      @param  dest:   le fichier destination
157         */
158  public boolean copy( RemoteFile src, RemoteFile dest ) throws RemoteException {
159        final String ERROR = "Had a problem copying '" + src + "' to '" + dest + "' !";
160        boolean success = false;
161        try {
162                        RemoteFileManager manager = dest.getFileManager( );
163                        if ( manager.equals(this) ) {
164                        ArrayList args = new ArrayList( );
165                        args.add( src );
166                        args.add( dest );
167                                RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.COPY, args );
168                        server.postEventWithResult( evt );
169                        Boolean result = (Boolean)evt.getResult( );
170                        success = result.booleanValue( );
171                        }
172                        else {
173                                success = manager.copy( src, dest );
174                        }
175    }
176        catch ( RemoteException remoteException ) {
177                if ( DEBUG ) { Trace.debug( this, ERROR, remoteException ); }
178        }
179        catch ( Exception exception ) {
180                if ( DEBUG ) { Trace.debug( this, ERROR, exception ); }
181        }
182                return success;
183  }
184 
185        /**
186         *      <p>Supprimer un fichier distant.</p>
187         *
188         *      @param  file:   le fichier à supprimer
189         */
190  public boolean delete( RemoteFile file ) throws RemoteException {
191        final String ERROR = "Had a problem deleting '" + file + "' !";
192        boolean success = false;
193        try {
194                        RemoteFileManager manager = file.getFileManager( );
195                        if ( manager.equals(this) ) {
196                                if ( exists(file) )
197                                {
198                                        ArrayList args = new ArrayList( );
199                                args.add( file );
200                                        RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.DELETE, args );
201                                server.postEventWithResult( evt );
202                                Boolean result = (Boolean)evt.getResult( );
203                                success = result.booleanValue( );
204                                }
205                                else
206                                {
207                                        return true;
208                                }
209                        }
210                        else {
211                        // -------------------------------------------
212              // Ask the destination manager to retrieve the
213              // source file for us.
214                        // -------------------------------------------
215                                success = manager.delete( file );
216                        }
217    }
218        catch ( RemoteException remoteException ) {
219                if ( DEBUG ) { Trace.debug( this, ERROR, remoteException ); }
220        }
221        catch ( IOException ioProblem ) {
222                if ( DEBUG ) { Trace.debug( this, ERROR, ioProblem ); }
223        }
224        catch ( Exception exception ) {
225                if ( DEBUG ) { Trace.debug( this, ERROR, exception ); }
226        }
227                return success;
228  }
229 
230        /**
231         *      Lister les fichiers distant d'un hôte.
232         *      On considère que le répertoire de base des fichiers est le répertoire passé en argument.
233         *
234         *      @param  directory:      le répertoire distant
235         */
236  public ArrayList list( RemoteFile directory ) throws RemoteException {
237        ArrayList remoteFiles = null;
238        String ERROR = "Had a problem listing '" + directory + "' !";
239        try {
240                        RemoteFileManager manager = directory.getFileManager( );
241                // -------------------------------------------
242      // List the files in the directory
243                // -------------------------------------------
244                        if ( manager.equals(this) ) {
245                        ArrayList args = new ArrayList( );
246                        args.add( directory );
247                                RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.LIST, args );
248                        server.postEventWithResult( evt );
249                        remoteFiles = (ArrayList)evt.getResult( );
250                        }
251                // -------------------------------------------
252      // Ask the destination manager to list the
253      // directory for us.
254                // -------------------------------------------
255                        else {
256                                remoteFiles = manager.list( directory );
257                        }
258    }
259        catch ( RemoteException remoteException ) {
260                if ( DEBUG ) { Trace.debug( this, ERROR, remoteException ); }
261        }
262        catch ( Exception exception ) {
263                if ( DEBUG ) { Trace.debug( this, ERROR, exception ); }
264        }
265                return remoteFiles;
266  }
267 
268        /**
269         *      <p>Transférer un fichier distant.</p>
270         *
271         *      @param  src:    le fichier source
272         *      @param  dest:   le fichier destination
273         */
274  public boolean move( RemoteFile src, RemoteFile dest ) throws RemoteException {
275        String ERROR = "Had a problem moving '" + src + "' to '" + dest + "' !";
276        boolean success = false;
277                // -------------------------------------------
278                // Debugging
279                // -------------------------------------------
280    if ( DEBUG ) { Trace.debug( this, IF_REMOTE_FILE_MANAGER + " moving files." ); }
281   
282        try {
283                // -------------------------------------------
284      // Move the file src to dest
285                // -------------------------------------------
286                        RemoteFileManager manager = dest.getFileManager( );
287                        if ( manager.equals(this) ) {
288                        ArrayList args = new ArrayList( );
289                        args.add( src );
290                        args.add( dest );
291                                RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.MOVE, args );
292                        server.postEventWithResult( evt );
293                        Boolean result = (Boolean)evt.getResult( );
294                        success = result.booleanValue( );
295                        }
296                // -------------------------------------------
297      // Ask the destination manager to move
298      // the file for us.
299                // -------------------------------------------
300                        else {
301                                success = manager.move( src, dest );
302                        }
303    }
304        catch ( RemoteException remoteException ) {
305                if ( DEBUG ) { Trace.debug( this, ERROR, remoteException ); }
306        }
307        catch ( Exception exception ) {
308                if ( DEBUG ) { Trace.debug( this, ERROR, exception ); }
309        }
310                return success;
311  }
312 
313 
314        /**
315         *      Récupérer un fichier distant sur cette hôte.
316         *
317         *      @param  remoteFile:     le fichier source à rapatrier
318         *
319         *      @return un File indiquant le fichier temporaire; l'appelant doit le détruire lorsqu'il a terminé
320         */
321  public File retrieve( RemoteFile file ) throws RemoteException {
322        final String ERROR = "Had a problem retrieving '" + file + "' !";
323        File retrieved = null;
324        try {
325                // -------------------------------------------
326      // Move the file src to dest
327                // -------------------------------------------
328                        RemoteFileManager manager = file.getFileManager( );
329                ArrayList args = new ArrayList( );
330                args.add( file );
331                        RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.RETRIEVE, args );
332                server.postEventWithResult( evt );
333                retrieved = (File)evt.getResult( );
334    }
335        catch ( RemoteException remoteException ) {
336                if ( DEBUG ) { Trace.debug( this, ERROR, remoteException ); }
337        }
338        catch ( Exception exception ) {
339                if ( DEBUG ) { Trace.debug( this, ERROR, exception ); }
340        }
341                return retrieved;
342  }
343 
344  /**
345   *    <p>Retrieves the local file corresponding a remote file on local</p>
346   *    <p>Return value is null if file is not available with this remote file manager.</p>
347   *
348         *      @param  remoteFile:     le fichier source à rapatrier
349         *
350         *      @return un File indiquant le fichier en local
351   */
352  public File getLocalFile( RemoteFile localFile ) throws RemoteException, IOException {
353        try {
354                RemoteFileManager distant = localFile.getFileManager( );
355                if ( distant.equals(this) ) {
356                    return localFile.getFile( );
357                }
358          }
359          catch ( NotBoundException notBound ) {
360                if ( DEBUG ) { Trace.debug( this, "RemoteFileManager not bound to " + localFile, notBound ); }
361          }
362          catch ( MalformedURLException badURL ) {
363                if ( DEBUG ) { Trace.debug( this, "Unable to locate RemoteFileManager for " + localFile, badURL ); }
364          }
365          return null;
366  }
367
368  /**
369   *    <p>Create a remote file representing a directory.
370   *    If the remote file is handled by this server, we delegat to the local
371   *    file manager. If not we forward the request to the <code>RemoteFile</code>'s server.
372   *    </p>
373   *    @param  directory:      the remote directory to create
374   *
375   *    @return true if the directory creation succeeded, false otherwise
376   */
377        public boolean makeDir( RemoteFile directory ) throws RemoteException {
378                boolean success = false;
379    if ( DEBUG ) { Trace.debug( this, "Creating directory '" + directory + "'" ); }
380                try {
381            RemoteFileManager remoteManager = directory.getFileManager( );
382            if ( remoteManager.equals(this) ) {
383                FileManager localFileManager = (FileManager)FileManager.instance( FileManager.class.toString() );
384                // ATTENTIOn CORECTIOn A TESTERT ET RETESTER
385                // return localFileManager.mkdir( directory.getPath() );
386                //
387                return localFileManager.mkdir( directory.getAbsolutePath() );
388                // success = true;
389            }
390            else {
391                success = remoteManager.makeDir( directory );
392            }
393                }
394                catch ( Exception exception ) {
395                        if ( DEBUG ) { Trace.debug( this, "Had a problem creating '" + directory + "' !", exception ); }
396                }
397                return success;
398        }
399         
400  /**
401   *    <p>Delete a remote file representing a directory.
402   *    If the remote file is handled by this server, we delegate to the local
403   *    file manager. If not we forward the request to the <code>RemoteFile</code>'s server.
404   *    </p>
405   *    @param  directory:      the remote directory to remove files from
406   */
407        public boolean deleteDir( RemoteFile directory ) throws RemoteException {
408    if ( DEBUG ) { Trace.debug( this, "Deleting directory " + directory ); }
409                try {
410            RemoteFileManager remoteManager = directory.getFileManager( );
411            if ( remoteManager.equals(this) ) {
412                FileManager localFileManager = (FileManager)FileManager.instance( FileManager.class.toString() );
413                localFileManager.deleteAllDir( directory.getPath() );
414                return true;
415            }
416            else {
417                return remoteManager.deleteDir( directory );
418            }
419                }
420                catch ( Exception exception ) {
421                        if ( DEBUG ) { Trace.debug( this, "Had a problem deleting '" + directory + "' !", exception ); }
422                }
423                return false;
424        }
425
426        /**
427         *      <p>Determine the size, in bytes, of the file or of all the files in a directory.</p>
428         *
429         *      @param directory:       the file or directory
430         *
431         *      @return the size of the file or directory; the size of a directory is the sum of all files within it and its sub-directories
432         */
433        public long size( RemoteFile directory ) throws RemoteException {
434        long length = 0;
435        final String ERROR = "Had a problem obtaining size of " + directory;
436        try {
437                // -------------------------------------------
438      // We retrieve the size of the directory of file.
439                // -------------------------------------------
440      RemoteFileManager remoteManager = directory.getFileManager( );
441      if ( remoteManager.equals(this) ) {
442//                              ArrayList args = new ArrayList( );
443//                              args.add( directory );
444//                                      RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.SIZE, args );
445//                              server.postEventWithResult( evt );
446//                              Long size = (Long)evt.getResult( );
447//                              length = size.longValue( );
448        // calcul réel par appel au local fileManager
449                        File toList = directory.getFileManager().getLocalFile( directory );
450                FileManager localFileManager = (FileManager)FileManager.instance( FileManager.class.toString() );
451                return localFileManager.size( toList );
452      }
453                // -------------------------------------------
454      // Ask the other remote manager to retrieve
455      //  the source file for us.
456                // -------------------------------------------
457      else {
458        length = remoteManager.size( directory );
459      }
460    }
461        catch ( RemoteException remoteException ) {
462                if ( DEBUG ) { Trace.debug( this, ERROR, remoteException ); }
463        }
464        catch ( IOException ioProblem ) {
465                if ( DEBUG ) { Trace.debug( this, ERROR, ioProblem ); }
466        }
467        catch ( Exception exception ) {
468                if ( DEBUG ) { Trace.debug( this, ERROR, exception ); }
469        }
470    if ( DEBUG ) { Trace.debug( this, "Size of files in remote directory: " + length + " bytes" ); }
471                return length;
472        }
473         
474          /**
475           *    <p>Determine if a remote file exists.</p>
476           *
477           *    @param  file: remote file to verify
478           *
479           *    @return true if the file exists, false otherwise
480           */
481        public boolean exists( RemoteFile file ) throws RemoteException {
482                boolean exists = false;
483                try {
484                        RemoteFileManager manager = file.getFileManager( );
485                        if ( manager.equals(this) ) {
486                        ArrayList args = new ArrayList( );
487                        args.add( file );
488                                RemoteFileServerEvent evt = new RemoteFileServerEvent( RemoteFileServerEvent.EXISTS, args );
489                        server.postEventWithResult( evt );
490                        Boolean result = (Boolean)evt.getResult( );
491                        exists = result.booleanValue( );
492                        }
493                        else {
494                                exists = manager.exists( file );
495                        }
496                }
497                catch ( NotBoundException notRunning ) {
498                        if ( DEBUG ) { Trace.debug( this, "Remote Server not bound", notRunning ); }
499                }
500                catch ( MalformedURLException badURL ) {
501                        if ( DEBUG ) { Trace.debug( this, "Invalid file name " + file, badURL ); }
502                }
503                catch ( IOException ioProblem ) {
504                        if ( DEBUG ) { Trace.debug( this, "Invalid file name " + file, ioProblem ); }
505                }
506                catch ( Exception e ) {
507                        if ( DEBUG ) { Trace.debug( this, "Error checking existence of file " + file, e ); }
508                }
509                finally {
510                        return exists;
511                }
512        }
513
514
515  /**
516   *    <p>Nettoyer les espaces temporaire utilisés sur cette machine.</p>
517   *
518   *    @param  int : l'identifiant de la commande
519   */
520        public void cleanTmpDir(int orderId) throws RemoteException {
521                FileManager localFileManager = (FileManager)FileManager.instance( FileManager.class.toString() );
522                try {
523                if ( DEBUG ) { Trace.debug( this, " TRYING TO CLEAN ARCHIVE DIR :" + localFileManager.getArchiveOrderDir(orderId)) ;}
524                        localFileManager.deleteAllDir(localFileManager.getArchiveOrderDir(orderId));
525                }
526                catch ( Exception e ) {
527                        if ( DEBUG ) { Trace.debug( this, "Error ", e ); }
528                }
529//              Order tempOrder = new Order(orderId);
530//              try {
531//              if ( DEBUG ) { Trace.debug( this, " TRYING TO CLEAN SERVICE DIR :" + localFileManager.getServiceOrderDir(tempOrder)) ;}
532//                      localFileManager.deleteAllDir(localFileManager.getServiceOrderDir(tempOrder));
533//              }
534//              catch ( Exception e ) {
535//                      if ( DEBUG ) { Trace.debug( this, "Error ", e ); }
536//              }
537//              try {
538//              if ( DEBUG ) { Trace.debug( this, " TRYING TO CLEAN TEMP DIR :" + localFileManager.getTempOrderDir(tempOrder)) ;}
539//                      localFileManager.deleteAllDir(localFileManager.getTempOrderDir(tempOrder));
540//              }
541//              catch ( Exception e ) {
542//                      if ( DEBUG ) { Trace.debug( this, "Error ", e ); }
543//              }
544        }
545
546          /**
547           *    <p>Execute the RMI Remote File Server.</p>
548           *
549           *    @param  args: command-line arguments; requires host name as first and only arg.
550           *
551           */
552  public static void main(String[] args) {
553        /*
554      if ( System.getSecurityManager() == null ) {
555          System.setSecurityManager( new RMISecurityManager() );
556      }
557      */
558      String name = "//" + args[0] + "/" + IF_REMOTE_FILE_MANAGER;
559      try {
560          Naming.rebind( name, new AtaRemoteFileServer() );
561          System.out.println( IF_REMOTE_FILE_MANAGER + " bound" );
562      } catch ( Exception e ) {
563          System.err.println( IF_REMOTE_FILE_MANAGER + " exception: " + e.getMessage() );
564          e.printStackTrace( );
565      }
566  }
567}
568 
Note: See TracBrowser for help on using the repository browser.