Statistics
| Revision:

root / branches / v2_0_0_prep / libraries / libRemoteServices / src / org / gvsig / remoteclient / taskplanning / retrieving / RequestManager.java @ 29671

History | View | Annotate | Download (5.97 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

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

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

    
135

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