KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > update > core > Utilities


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.core;
12
13 import java.io.*;
14 import java.text.DateFormat JavaDoc;
15 import java.util.Date JavaDoc;
16 import java.util.HashMap JavaDoc;
17 import java.util.Locale JavaDoc;
18 import java.util.Map JavaDoc;
19
20 import org.eclipse.core.runtime.*;
21 import org.eclipse.update.core.model.*;
22 import org.eclipse.update.internal.core.*;
23
24 /**
25  * This class is a collection of utility functions that can be
26  * used for install processing
27  * <p>
28  * <b>Note:</b> This class/interface is part of an interim API that is still under development and expected to
29  * change significantly before reaching stability. It is being made available at this early stage to solicit feedback
30  * from pioneering adopters on the understanding that any code that uses this API will almost certainly be broken
31  * (repeatedly) as the API evolves.
32  * </p>
33  */

34 public class Utilities {
35
36     private static Map JavaDoc entryMap;
37     private static final DateFormat JavaDoc dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.getDefault());
38     private static long tmpseed = (new Date JavaDoc()).getTime();
39     private static String JavaDoc dirRoot = null;
40
41     /**
42      * Returns a new working directory (in temporary space). Ensures
43      * the directory exists. Any directory levels that had to be created
44      * are marked for deletion on exit.
45      *
46      * @return working directory
47      * @exception IOException
48      * @since 2.0
49      */

50     public static synchronized File createWorkingDirectory() throws IOException {
51
52         if (dirRoot == null) {
53             dirRoot = System.getProperty("java.io.tmpdir"); //$NON-NLS-1$
54
// in Linux, returns '/tmp', we must add '/'
55
if (!dirRoot.endsWith(File.separator))
56                 dirRoot += File.separator;
57
58             // on Unix/Linux, the temp dir is shared by many users, so we need to ensure
59
// that the top working directory is different for each user
60
if (!Platform.getOS().equals("win32")) { //$NON-NLS-1$
61
String JavaDoc home = System.getProperty("user.home"); //$NON-NLS-1$
62
home = Integer.toString(home.hashCode());
63                 dirRoot += home + File.separator;
64             }
65             dirRoot += "eclipse" + File.separator + ".update" + File.separator + Long.toString(tmpseed) + File.separator; //$NON-NLS-1$ //$NON-NLS-2$
66
}
67
68         String JavaDoc tmpName = dirRoot + Long.toString(++tmpseed) + File.separator;
69
70         File tmpDir = new File(tmpName);
71         verifyPath(tmpDir, false);
72         if (!tmpDir.exists())
73             throw new FileNotFoundException(tmpName);
74         return tmpDir;
75     }
76
77     /**
78      * Create a new working file. The file is marked for deletion on exit.
79      *
80      * @see #lookupLocalFile(String)
81      * @param tmpDir directory location for new file. Any missing directory
82      * levels are created (and marked for deletion on exit)
83      * @param name optional file name, or <code>null</code>. If name is not
84      * specified, a temporary name is generated.
85      * @return created working file
86      * @exception IOException
87      * @since 2.0
88      */

89     public static synchronized File createLocalFile(File tmpDir, String JavaDoc name) throws IOException {
90         // create the local file
91
File temp;
92         String JavaDoc filePath;
93         if (name != null) {
94             // create file with specified name
95
filePath = name.replace('/', File.separatorChar);
96             if (filePath.startsWith(File.separator))
97                 filePath = filePath.substring(1);
98             temp = new File(tmpDir, filePath);
99         } else {
100             // create file with temp name
101
temp = File.createTempFile("eclipse", null, tmpDir); //$NON-NLS-1$
102
}
103         temp.deleteOnExit();
104         verifyPath(temp, true);
105
106         return temp;
107     }
108
109     /**
110      * The file is associated with a lookup key.
111      * @param key optional lookup key, or <code>null</code>.
112      * @param temp the local working file
113      * @since 2.0.2
114      */

115     public synchronized static void mapLocalFile(String JavaDoc key, File temp) {
116         // create file association
117
if (key != null) {
118             if (entryMap == null)
119                 entryMap = new HashMap JavaDoc();
120             entryMap.put(key, temp);
121         }
122     }
123
124     /**
125      * Returns a previously cached local file (in temporary area) matching the
126      * specified key.
127      *
128      * @param key lookup key
129      * @return cached file, or <code>null</code>.
130      * @since 2.0
131      */

132     public static synchronized File lookupLocalFile(String JavaDoc key) {
133         if (entryMap == null)
134             return null;
135         return (File) entryMap.get(key);
136     }
137
138     /**
139      * Flushes all the keys from the local file map.
140      * Reinitialize the cache.
141      *
142      * @since 2.1
143      */

144     public synchronized static void flushLocalFile() {
145         entryMap = null;
146     }
147
148     /**
149      * Removes the specified key from the local file map. The file is
150      * not actually deleted until VM termination.
151      *
152      * @param key lookup key
153      * @since 2.0
154      */

155     public static synchronized void removeLocalFile(String JavaDoc key) {
156         if (entryMap != null)
157             entryMap.remove(key);
158     }
159
160     /**
161      * Copies specified input stream to the output stream. Neither stream
162      * is closed as part of this operation.
163      *
164      * @param is input stream
165      * @param os output stream
166      * @param monitor progress monitor
167      * @exception IOException
168      * @exception InstallAbortedException
169      * @since 2.0
170      */

171     public static void copy(InputStream is, OutputStream os, InstallMonitor monitor) throws IOException, InstallAbortedException {
172         long offset = UpdateManagerUtils.copy(is, os, monitor, 0);
173         if (offset != -1) {
174             if (monitor.isCanceled()) {
175                 String JavaDoc msg = Messages.Feature_InstallationCancelled;
176                 throw new InstallAbortedException(msg, null);
177             } else {
178                 throw new IOException();
179             }
180         }
181     }
182
183     /**
184      * Creates a CoreException from some other exception.
185      * The type of the CoreException is <code>IStatus.ERROR</code>
186      * If the exception passed as a parameter is also a CoreException,
187      * the new CoreException will contain all the status of the passed
188      * CoreException.
189      *
190      * @see IStatus#ERROR
191      * @param s exception string
192      * @param code the code reported
193      * @param e actual exception being reported
194      * @return a CoreException
195      * @since 2.0
196      */

197     public static CoreException newCoreException(String JavaDoc s, int code, Throwable JavaDoc e) {
198         String JavaDoc id = UpdateCore.getPlugin().getBundle().getSymbolicName();
199
200         // check the case of a multistatus
201
IStatus status;
202         if (e instanceof FeatureDownloadException)
203             return (FeatureDownloadException)e;
204         else if (e instanceof CoreException) {
205             if (s == null)
206                 s = ""; //$NON-NLS-1$
207
status = new MultiStatus(id, code, s, e);
208             IStatus childrenStatus = ((CoreException) e).getStatus();
209             ((MultiStatus) status).add(childrenStatus);
210             ((MultiStatus) status).addAll(childrenStatus);
211         } else {
212             StringBuffer JavaDoc completeString = new StringBuffer JavaDoc(""); //$NON-NLS-1$
213
if (s != null)
214                 completeString.append(s);
215             if (e != null) {
216                 completeString.append(" ["); //$NON-NLS-1$
217
String JavaDoc msg = e.getLocalizedMessage();
218                 completeString.append(msg!=null?msg:e.toString());
219                 completeString.append("]"); //$NON-NLS-1$
220
}
221             status = new Status(IStatus.ERROR, id, code, completeString.toString(), e);
222         }
223         CoreException ce = new CoreException(status);
224         
225         if ( e instanceof FatalIOException) {
226             ce = new CoreExceptionWithRootCause(status);
227             ((CoreExceptionWithRootCause)ce).setRootException(e);
228         }
229         /* for when we move to 1.5
230          if ( e instanceof CoreException) {
231             ce.initCause(e.getCause());
232         } else {
233             ce.initCause(e);
234         }
235         if (e != null)
236             ce.setStackTrace(e.getStackTrace());*/

237         return ce;
238     }
239
240     /**
241      * Creates a CoreException from some other exception.
242      * The type of the CoreException is <code>IStatus.ERROR</code>
243      * If the exceptionpassed as a parameter is also a CoreException,
244      * the new CoreException will contain all the status of the passed
245      * CoreException.
246      *
247      * @see IStatus#ERROR
248      * @param s exception string
249      * @param e actual exception being reported
250      * @return a CoreException
251      * @since 2.0
252      */

253     public static CoreException newCoreException(String JavaDoc s, Throwable JavaDoc e) {
254         return newCoreException(s, IStatus.OK, e);
255     }
256
257     /**
258      * Creates a CoreException from two other CoreException
259      *
260      * @param s overall exception string
261      * @param s1 string for first detailed exception
262      * @param s2 string for second detailed exception
263      * @param e1 first detailed exception
264      * @param e2 second detailed exception
265      * @return a CoreException with multi-status
266      * @since 2.0
267      */

268     public static CoreException newCoreException(String JavaDoc s, String JavaDoc s1, String JavaDoc s2, CoreException e1, CoreException e2) {
269         String JavaDoc id = UpdateCore.getPlugin().getBundle().getSymbolicName();
270         if (s == null)
271             s = ""; //$NON-NLS-1$
272

273         IStatus childStatus1 = e1.getStatus();
274         IStatus childStatus2 = e2.getStatus();
275         int code = (childStatus1.getCode() == childStatus2.getCode()) ? childStatus1.getCode() : IStatus.OK;
276         MultiStatus multi = new MultiStatus(id, code, s, null);
277
278         multi.add(childStatus1);
279         multi.addAll(childStatus1);
280         multi.add(childStatus2);
281         multi.addAll(childStatus2);
282
283         return new CoreException(multi);
284     }
285
286     /**
287      * Formats a Date based on the default Locale
288      * If teh Date is <code>null</code> returns an empty String
289      *
290      * @param date the Date to format
291      * @return the formatted Date as a String
292      * @since 2.0
293      */

294     public static String JavaDoc format(Date JavaDoc date) {
295         if (date == null)
296             return ""; //$NON-NLS-1$
297
return dateFormat.format(date);
298     }
299
300     /**
301      * Perform shutdown processing for temporary file handling.
302      * This method is called when platform is shutting down.
303      * It is not intended to be called at any other time under
304      * normal circumstances. A side-effect of calling this method
305      * is that the contents of the temporary directory managed
306      * by this class are deleted.
307      *
308      * @since 2.0
309      */

310     public static void shutdown() {
311         if (dirRoot == null)
312             return;
313
314         File temp = new File(dirRoot); // temp directory root for this run
315
cleanupTemp(temp);
316         temp.delete();
317     }
318
319     private static void cleanupTemp(File root) {
320         File[] files = root.listFiles();
321         for (int i = 0; files != null && i < files.length; i++) {
322             if (files[i].isDirectory())
323                 cleanupTemp(files[i]);
324             files[i].delete();
325         }
326     }
327
328     private static void verifyPath(File path, boolean isFile) {
329         // if we are expecting a file back off 1 path element
330
if (isFile) {
331             if (path.getAbsolutePath().endsWith(File.separator)) {
332                 // make sure this is a file
333
path = path.getParentFile();
334                 isFile = false;
335             }
336         }
337
338         // already exists ... just return
339
if (path.exists())
340             return;
341
342         // does not exist ... ensure parent exists
343
File parent = path.getParentFile();
344         verifyPath(parent, false);
345
346         // ensure directories are made. Mark files or directories for deletion
347
if (!isFile)
348             path.mkdir();
349         path.deleteOnExit();
350     }
351 }
352
Popular Tags