Statistics
| Revision:

svn-gvsig-desktop / trunk / libraries / libRemoteServices / src / org / gvsig / remoteClient / taskplanning / retrieving / RequestManager.java @ 5230

History | View | Annotate | Download (6.02 KB)

1
/*
2
 * Created on 01-oct-2005
3
 */
4
package org.gvsig.remoteClient.taskplanning.retrieving;
5

    
6
import java.io.File;
7
import java.net.MalformedURLException;
8
import java.util.Hashtable;
9
import java.util.TreeMap;
10

    
11
import org.gvsig.remoteClient.taskplanning.IQueue;
12
import org.gvsig.remoteClient.taskplanning.IRunnableTask;
13

    
14
/**
15
 * pa administrar les tasques (la hist?ria aquella
16
 *  de que hi haja una cola per a cada servidor)
17
 * @author Luis W. Sevilla (sevilla_lui@gva.es)
18
 */
19
public class RequestManager {
20
        private boolean debug = true;
21
    
22
        private static RequestManager instance;
23
        private TreeMap serversTable = new TreeMap();
24
        private RequestManager() {} // Avoid public instantiation
25
         
26
        public static RequestManager getInstance() {
27
                if (instance == null)
28
                        instance = new RequestManager();
29
                return instance;
30
        }
31
        
32
        
33
        public URLRetrieveTask addURLRequest(URLRequest request, RetrieveListener listener) {
34
                try {
35
                        
36
                        // TODO canviar per a quetorne el Request antic, que la request guarde el
37
                        // seu estat aix? com la llista de listeners
38
                        File f = getPreviousDownloadedURLRequest(request);
39
                        
40
                        if (f!=null) {
41
                                // The file was already requested and it is in the cache or
42
                                // the download is in process
43
                                
44
                                // Overwrite the file name with the file in the cache's one.
45
                                request.setFileName(f.getAbsolutePath());
46
                                System.out.println(request.getUrl()+" is cached at '"+f.getAbsolutePath()+"'");
47
                                
48

    
49
                                // get this server's task queue
50
                                RetrieveQueue serverQueue = (RetrieveQueue) getQueue(request.getHost());
51
                                
52
                                // Look up the previous cached jobs
53
                                
54
                                URLRetrieveTask workingTask = serverQueue.getURLPreviousRequest(request);
55
                                if (workingTask == null) {
56
                                        // Task already done. Notify listener
57
                                        if (debug)
58
                                                System.err.println("done job found: "+request.getUrl());
59
                                        RetrieveEvent event = new RetrieveEvent();
60
                                        event.setType(RetrieveEvent.REQUEST_FINISHED);
61
                                        listener.transferEventReceived(event);
62
                                        
63
                                } else {
64
                                        // The task is working yet, will register the listener
65
                                        
66
                                        // TODO no va b?... perqu? la cola va buidant-se molt r?pidament
67
                                        // per a fer que vaja tamb? hi hauria que registrar en cache
68
                                        // lo que s'est? baixant al principi de l'execute();
69
                                        if (debug)
70
                                                System.err.println("working job found: "+request.getUrl());
71
                                        workingTask.addRetrieveListener(listener);
72
                                        
73
                                }
74
                        } else {
75
                                // Pick an unrepeatable fileName
76
                                String host = request.getHost();
77
                                String fileName = request.getFileName();
78
                                File tempDir = new File(tempDirectoryPath);
79
                                if (!tempDir.exists())
80
                                        tempDir.mkdir();
81
                                String fileNamePrefix = tempDirectoryPath + 
82
                                                                                        File.separator + host + 
83
                                                                                        "-" ;
84
                                if (fileName.startsWith(fileNamePrefix))
85
                                        fileName = fileName.substring(fileNamePrefix.length(), fileName.length());
86
                                
87
                                // get this server's task queue
88
                                RetrieveQueue serverQueue = (RetrieveQueue) getQueue(request.getHost());
89
                                
90
                                
91
                                fileName = fileNamePrefix + fileName;
92
                                
93
                                request.setFileName(fileName);
94
                                
95
                                // TODO
96
                                // jo ac? comprovaria quin protocol, m?tode, host, etc... i crearia un
97
                                // objecte que tractara la desc?rrega segons el m?tode que li toca.
98
                                // algo en plan Strategy's
99
                                //
100
                                // per exemple si fem URLRetrieveTask una abstracta i tenim
101
                                // 
102
                                // GET de tota la vida
103
                                // serverQueue.put(new HTTPGetRetrieveTask(request, listener));
104
                                //
105
                                // POST
106
                                // serverQueue.put(new HTTPPostRetrieveTask(request, listener));
107
                                //
108
                                // FTP
109
                                // serverQueue.put(new FTPRetrieveTask(request, listener));
110
                                //
111
                                // ????Xarxa local?????
112
                                // serverQueue.put(new SMBRetrieveTask(request, listener));
113
                                
114
                                // Enqueue the request and the listener will be notified when done.
115
                                URLRetrieveTask task = new URLRetrieveTask(request, listener);
116
                                return (URLRetrieveTask) serverQueue.put(task);
117
                        }
118
                } catch (MalformedURLException e) {
119
                        e.printStackTrace();
120
                }
121
                return null;
122
        }
123
        
124
        private IQueue getQueue(String hostName) {
125
                RetrieveQueue queue = null;
126
                if (serversTable.containsKey(hostName))
127
                        queue = (RetrieveQueue) serversTable.get(hostName);
128
                else {
129
                        // crea la cola
130
                        queue = new RetrieveQueue(hostName);
131
                        // pone la cola del server en marcha.
132
                }
133
                return queue;
134
        }
135

    
136

    
137
        private Hashtable downloadedFiles;
138
        private final String tempDirectoryPath = System.getProperty("java.io.tmpdir")+"tmp-andami";
139
        /**
140
     * Remove an URL from the system cache. The file will remain in the file
141
     * system for further eventual uses.
142
     * @param request
143
     */
144
        public void removeURLRequest(URLRequest request) {
145
                if (downloadedFiles != null && downloadedFiles.containsKey(request))
146
                        downloadedFiles.remove(request);
147
        }
148
        /**
149
     * Adds an URL to the table of downloaded files for further uses. If the URL
150
     * already exists in the table its filePath value is updated to the new one and
151
     * the old file itself is removed from the file system.
152
     * 
153
     * @param url
154
     * @param filePath
155
     */
156
    protected void addDownloadedURLRequest(URLRequest request, String filePath){
157
        if (downloadedFiles==null)
158
            downloadedFiles = new Hashtable();
159
        String fileName = (String) downloadedFiles.put(request, filePath);
160
        if (fileName!=null){
161
            File f = new File(fileName);
162
            if (f.exists())
163
                f.delete();
164
        }
165
    }
166
    /**
167
     * Returns the content of this URL as a file from the file system.<br>
168
     * <p>
169
     * If the URL has been already downloaded in this session and notified 
170
     * to the system using the static <b>Utilities.addDownloadedURL(URL)</b>
171
     * method, it can be restored faster from the file system avoiding to
172
     * download it again.
173
     * </p>
174
     * @param url
175
     * @return File containing this URL's content or null if no file was found.
176
     */
177
    private File getPreviousDownloadedURLRequest(URLRequest request){
178
        File f = null;
179
        if (downloadedFiles!=null && downloadedFiles.containsKey(request)){
180
            String filePath = (String) downloadedFiles.get(request);
181
            f = new File(filePath);
182
        }
183
        return f;
184
    }
185
    
186
}