KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > internal > core > InternalSiteManager


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.update.internal.core;
12
13 import java.io.File JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.net.MalformedURLException JavaDoc;
16 import java.net.URL JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.Map JavaDoc;
19
20 import org.eclipse.core.runtime.CoreException;
21 import org.eclipse.core.runtime.IProgressMonitor;
22 import org.eclipse.core.runtime.IStatus;
23 import org.eclipse.core.runtime.MultiStatus;
24 import org.eclipse.core.runtime.NullProgressMonitor;
25 import org.eclipse.osgi.util.NLS;
26 import org.eclipse.update.configuration.ILocalSite;
27 import org.eclipse.update.core.ISite;
28 import org.eclipse.update.core.ISiteFactory;
29 import org.eclipse.update.core.ISiteFactoryExtension;
30 import org.eclipse.update.core.JarContentReference;
31 import org.eclipse.update.core.Site;
32 import org.eclipse.update.core.Utilities;
33 import org.eclipse.update.core.model.InvalidSiteTypeException;
34 import org.eclipse.update.internal.core.connection.ConnectionFactory;
35 import org.eclipse.update.internal.core.connection.IResponse;
36 import org.eclipse.update.internal.model.ITimestamp;
37
38 /**
39  *
40  */

41 public class InternalSiteManager {
42
43     public static ILocalSite localSite;
44
45     public static final String JavaDoc DEFAULT_SITE_TYPE = SiteURLContentProvider.SITE_TYPE;
46     private static final String JavaDoc DEFAULT_EXECUTABLE_SITE_TYPE = SiteFileContentProvider.SITE_TYPE;
47
48     private static Map JavaDoc estimates;
49
50     // cache found sites
51
private static Map JavaDoc sites = new HashMap JavaDoc();
52     // cache http updated url
53
private static Map JavaDoc httpSitesUpdatedUrls = new HashMap JavaDoc();
54     // cache timestamps
55
private static Map JavaDoc siteTimestamps = new HashMap JavaDoc();
56     public static boolean globalUseCache = true;
57
58     // true if an exception occured creating localSite
59
// so we cache it and don't attempt to create it again
60
private static CoreException exceptionOccured = null;
61
62     /*
63      * @see SiteManager#getLocalSite()
64      */

65     public static ILocalSite getLocalSite() throws CoreException {
66         return internalGetLocalSite();
67     }
68
69     /*
70      * Internal call if optimistic reconciliation needed
71      */

72     private static ILocalSite internalGetLocalSite() throws CoreException {
73
74         // if an exception occured while retrieving the Site
75
// rethrow it
76
if (exceptionOccured != null)
77             throw exceptionOccured;
78
79         if (localSite == null) {
80             try {
81                 localSite = LocalSite.internalGetLocalSite();
82             } catch (CoreException e) {
83                 exceptionOccured = e;
84                 throw e;
85             }
86         }
87         return localSite;
88     }
89     
90     private static boolean isValidCachedSite(URL JavaDoc siteURL) {
91         if (!sites.containsKey(siteURL.toExternalForm()))
92             return false;
93             
94         Long JavaDoc timestamp = (Long JavaDoc)siteTimestamps.get(siteURL);
95         if (timestamp == null)
96             return false;
97         long localLastModified = timestamp.longValue();
98         
99         return UpdateManagerUtils.isSameTimestamp(siteURL, localLastModified);
100     }
101
102     /*
103      * @see ILocalSite#getSite(URL)
104      */

105     public static ISite getSite(URL JavaDoc siteURL, boolean useCache, IProgressMonitor monitor) throws CoreException {
106         ISite site = null;
107         if (monitor==null) monitor = new NullProgressMonitor();
108
109         if (siteURL == null)
110             return null;
111
112         // use cache if set up globally (globalUseCache=true)
113
// and passed as parameter (useCache=true)
114
if (httpSitesUpdatedUrls.containsKey(siteURL.toExternalForm())) {
115             siteURL = (URL JavaDoc)httpSitesUpdatedUrls.get(siteURL.toExternalForm());
116         }
117         String JavaDoc siteURLString = siteURL.toExternalForm();
118         if ((useCache && globalUseCache) && isValidCachedSite(siteURL)) {
119             site = (ISite) sites.get(siteURLString);
120             UpdateCore.getPlugin().getUpdateSession().markVisited(site.getURL());
121             return site;
122         }
123         
124         // try adding "eclipse" to the site url, in case this is an extension site
125
if ("file".equals(siteURL.getProtocol()) ) { //$NON-NLS-1$
126
File JavaDoc f = new File JavaDoc(siteURL.getFile());
127             if (f.isDirectory() && !"eclipse".equals(f.getName())) { //$NON-NLS-1$
128
f = new File JavaDoc(f, "eclipse"); //$NON-NLS-1$
129
try {
130                     if ((useCache && globalUseCache) && isValidCachedSite(f.toURL())) {
131                         site = (ISite) sites.get(f.toURL().toExternalForm());
132                         return site;
133                     }
134                 } catch (MalformedURLException JavaDoc e) {
135                 }
136             }
137         }
138
139         // consider file protocol also if the URL points to a directory
140
// and no site.xml exist
141
// if the user points to a file, consider DEFAULT_SITE_TYPE
142
// site.xml will have to specify the type
143
boolean fileProtocol = "file".equalsIgnoreCase(siteURL.getProtocol()); //$NON-NLS-1$
144
boolean directoryExists = false;
145         if (fileProtocol) {
146             File JavaDoc dir;
147             dir = new File JavaDoc(siteURL.getFile());
148             if (dir != null && dir.isDirectory()) {
149                 if (!(new File JavaDoc(dir, Site.SITE_XML).exists()))
150                     directoryExists = true;
151             }
152         }
153
154         //PERF: if file: <path>/ and directory exists then consider executable
155
monitor.beginTask(Messages.InternalSiteManager_ConnectingToSite, 8);
156         if (fileProtocol && directoryExists) {
157             site = attemptCreateSite(DEFAULT_EXECUTABLE_SITE_TYPE, siteURL, monitor);
158             monitor.worked(4); // only one attempt
159
} else {
160             try {
161                 monitor.worked(3);
162                 site = attemptCreateSite(DEFAULT_SITE_TYPE, siteURL, monitor);
163                 monitor.worked(1);
164             } catch (CoreException preservedException) {
165                 if (!monitor.isCanceled()) {
166                     // attempt a retry is the protocol is file, with executbale type
167
if (!fileProtocol)
168                         throw preservedException;
169
170                     try {
171                         site = attemptCreateSite(DEFAULT_EXECUTABLE_SITE_TYPE, siteURL, monitor);
172                     } catch (CoreException retryException) {
173                         IStatus firstStatus = preservedException.getStatus();
174                         MultiStatus multi = new MultiStatus(firstStatus.getPlugin(), IStatus.OK, Messages.InternalSiteManager_FailedRetryAccessingSite, retryException);
175                         multi.addAll(firstStatus);
176                         throw preservedException;
177                     }
178                 }
179             }
180         }
181
182         if (site != null) {
183             sites.put(site.getURL().toExternalForm(), site);
184             UpdateCore.getPlugin().getUpdateSession().markVisited(site.getURL());
185             if (site instanceof ITimestamp) {
186                 siteTimestamps.put(site.getURL(), new Long JavaDoc(((ITimestamp)site).getTimestamp().getTime()));
187             } else {
188                 try {
189                     IResponse response = ConnectionFactory.get(URLEncoder.encode(siteURL));
190                     siteTimestamps.put(siteURL, new Long JavaDoc(response.getLastModified()));
191                 } catch (MalformedURLException JavaDoc e) {
192                 } catch (IOException JavaDoc e) {
193                 }
194             }
195         }
196
197         //flush the JarFile we may hold on to
198
// we keep the temp not to create them again
199
JarContentReference.shutdown(); // make sure we are not leaving jars open for this site
200

201         //flush mapping of downloaded JAR files
202
// FIXME : provide better cache flushing after 2.1
203
// FIXED: everything downloaded is cached and timestamped.
204
// Timestamps are compared to lastModifed on the server
205
// and we download only when there is a differenc
206
// Utilities.flushLocalFile();
207

208         return site;
209     }
210
211     /*
212      * Attempt to create a site
213      * if the site guessed is not the type found,
214      * attempt to create a type with the type found in the site.xml
215      */

216     private static ISite attemptCreateSite(String JavaDoc guessedTypeSite, URL JavaDoc siteURL, IProgressMonitor monitor) throws CoreException {
217         if (monitor == null) monitor = new NullProgressMonitor();
218         ISite site = null;
219
220         try {
221             monitor.worked(1);
222             site = createSite(guessedTypeSite, siteURL, monitor);
223             monitor.worked(1); // if no error, occurs the retry branch doesn't need to be executed
224
} catch (InvalidSiteTypeException e) {
225             if (monitor.isCanceled()) return null;
226
227             // the type in the site.xml is not the one expected
228
// attempt to use this type instead
229
//DEBUG:
230
if (UpdateCore.DEBUG && UpdateCore.DEBUG_SHOW_TYPE) {
231                 UpdateCore.debug("The Site :" + siteURL.toExternalForm() + " is a different type than the guessed type based on the protocol. new Type:" + e.getNewType()); //$NON-NLS-1$ //$NON-NLS-2$
232
}
233
234             try {
235                 if (e.getNewType() == null)
236                     throw e;
237                 site = createSite(e.getNewType(), siteURL, monitor);
238             } catch (InvalidSiteTypeException e1) {
239                 throw Utilities.newCoreException(NLS.bind(Messages.InternalSiteManager_UnableToCreateSiteWithType, (new String JavaDoc[] { e.getNewType(), siteURL.toExternalForm() })), e1);
240             }
241         }
242
243         return site;
244     }
245
246     /*
247      * create an instance of a class that implements ISite
248      *
249      * the URL can be of the following form
250      * 1 protocol://...../
251      * 2 protocol://.....
252      * 3 protocol://..../site.xml
253      * 4 protocol://...#...
254      *
255      * 1 If the file of the file of teh url ends with '/', attempt to open the stream.
256      * if it fails, add site.xml and attempt to open the stream
257      *
258      * 2 attempt to open the stream
259      * fail
260      * add '/site.xml' and attempt to open the stream
261      * sucess
262      * attempt to parse, if it fails, add '/site.xml' and attempt to open the stream
263      *
264      * 3 open the stream
265      *
266      * 4 open the stream
267      */

268     private static ISite createSite(String JavaDoc siteType, URL JavaDoc url, IProgressMonitor monitor) throws CoreException, InvalidSiteTypeException {
269         
270         if (monitor == null) monitor = new NullProgressMonitor();
271         //ISite site = null;
272
ISiteFactory factory = SiteTypeFactory.getInstance().getFactory(siteType);
273         URL JavaDoc fixedUrl;
274         
275         // see if we need to (and can) fix url by adding site.xml to it
276
try {
277             if ( (url.getRef() != null) || (url.getFile().endsWith(Site.SITE_XML) || (url.getProtocol().equalsIgnoreCase("file")))) { //$NON-NLS-1$
278
fixedUrl = url;
279             } else if (url.getFile().endsWith("/")) { //$NON-NLS-1$
280
fixedUrl = new URL JavaDoc(url, Site.SITE_XML);
281             } else {
282                 fixedUrl = new URL JavaDoc(url.getProtocol(), url.getHost(), url.getPort(), url.getFile() + "/" + Site.SITE_XML); //$NON-NLS-1$
283
}
284         } catch (MalformedURLException JavaDoc mue) {
285             fixedUrl = url;
286         }
287         
288         try {
289             try {
290                 monitor.worked(1);
291                 return createSite( factory, fixedUrl, url, monitor);
292             } catch (CoreException ce) {
293                 if (monitor.isCanceled())
294                     return null;
295             
296                 if (!fixedUrl.equals(url)) {
297                     // try with original url
298
return createSite( factory, url, url, monitor);
299                 } else if (url.getProtocol().equalsIgnoreCase("file") && ! url.getFile().endsWith(Site.SITE_XML)){ //$NON-NLS-1$
300
try {
301                         if (url.getFile().endsWith("/")) { //$NON-NLS-1$
302
return createSite(factory, new URL JavaDoc(url,
303                                     Site.SITE_XML), url, monitor);
304                         } else {
305                             return createSite(factory, new URL JavaDoc(url
306                                     .getProtocol(), url.getHost(), url
307                                     .getPort(), url.getFile()
308                                     + "/" + Site.SITE_XML), url, monitor); //$NON-NLS-1$
309
}
310                     } catch (MalformedURLException JavaDoc mue) {
311                         throw ce;
312                     }
313                 } else {
314                     throw ce;
315                 }
316             }
317         } catch(CoreException ce) {
318             throw Utilities.newCoreException(NLS.bind(Messages.InternalSiteManager_UnableToAccessURL, (new String JavaDoc[] { url.toExternalForm() })), ce);
319         }
320     }
321     
322     private static ISite createSite(ISiteFactory factory, URL JavaDoc url, URL JavaDoc originalUrl, IProgressMonitor monitor) throws CoreException, InvalidSiteTypeException {
323         
324         ISite site;
325             
326         site = createSite(factory, url, monitor);
327         httpSitesUpdatedUrls.put(originalUrl.toExternalForm(), url);
328         
329         return site;
330     }
331     
332     private static ISite createSite(ISiteFactory factory, URL JavaDoc url, IProgressMonitor monitor) throws CoreException, InvalidSiteTypeException {
333         if (factory instanceof ISiteFactoryExtension)
334             return ((ISiteFactoryExtension)factory).createSite(url, monitor);
335         else
336             return factory.createSite(url);
337     }
338
339     /*
340      * Creates a new site on the file system
341      * This is the only Site we can create.
342      *
343      * @param siteLocation
344      * @throws CoreException
345      */

346     public static ISite createSite(File JavaDoc siteLocation) throws CoreException {
347         ISite site = null;
348         if (siteLocation != null) {
349             try {
350                 URL JavaDoc siteURL = siteLocation.toURL();
351                 site = getSite(siteURL, false, null);
352             } catch (MalformedURLException JavaDoc e) {
353                 throw Utilities.newCoreException(NLS.bind(Messages.InternalSiteManager_UnableToCreateURL, (new String JavaDoc[] { siteLocation.getAbsolutePath() })), e);
354             }
355         }
356         return site;
357     }
358
359
360     /**
361      * Method downloaded.
362      * @param downloadSize size downloaded in bytes
363      * @param time time in seconds
364      * @param url
365      */

366     public static void downloaded(long downloadSize, long time, URL JavaDoc url) {
367         if (downloadSize <= 0 || time < 0)
368             return;
369         String JavaDoc host = url.getHost();
370         long sizeByTime = (time == 0) ? 0 : downloadSize / time;
371         Long JavaDoc value = new Long JavaDoc(sizeByTime);
372         if (estimates == null) {
373             estimates = new HashMap JavaDoc();
374         } else {
375             Long JavaDoc previous = (Long JavaDoc) estimates.get(host);
376             if (previous != null) {
377                 value = new Long JavaDoc((previous.longValue() + sizeByTime) / 2);
378             }
379         }
380         estimates.put(host, value);
381     }
382     /**
383      * Method getEstimatedTransferRate rate bytes/seconds.
384      * @param host
385      * @return long
386      */

387     public static long getEstimatedTransferRate(String JavaDoc host) {
388         if (estimates == null)
389             return 0;
390         Long JavaDoc value = (Long JavaDoc) estimates.get(host);
391         if (value == null)
392             return 0;
393         return value.longValue();
394     }
395
396 }
397
Popular Tags