001 package de.mospace.swing;
002
003 /*
004 * $Id: ExtensionInstaller.java 69 2007-10-24 21:57:43Z ringler $
005 * This class is part of the de.mospace.swing library.
006 * Copyright (C) 2006 Moritz Ringler
007 *
008 * This program is free software; you can redistribute it and/or
009 * modify it under the terms of the GNU General Public License
010 * as published by the Free Software Foundation; either version 2
011 * of the License, or (at your option) any later version.
012 *
013 * This program is distributed in the hope that it will be useful,
014 * but WITHOUT ANY WARRANTY; without even the implied warranty of
015 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
016 * GNU General Public License for more details.
017 *
018 * You should have received a copy of the GNU General Public License
019 * along with this program; if not, write to the Free Software
020 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
021 */
022 //To Do: check if we have a Sun JRE, if not warn that LaFInstaller might not work
023 import java.awt.Component;
024 import java.io.BufferedInputStream;
025 import java.io.BufferedOutputStream;
026 import java.io.File;
027 import java.io.FileInputStream;
028 import java.io.FileNotFoundException;
029 import java.io.FileOutputStream;
030 import java.io.IOException;
031 import java.io.InputStream;
032 import java.nio.channels.FileChannel;
033 import java.nio.channels.FileLock;
034 import java.util.Collections;
035 import java.util.Comparator;
036 import java.util.Iterator;
037 import java.util.List;
038 import java.util.jar.JarFile;
039 import java.util.logging.Logger;
040 import java.util.zip.ZipEntry;
041 import java.util.zip.ZipFile;
042 import javax.swing.Box;
043 import javax.swing.JDialog;
044 import javax.swing.JFileChooser;
045 import javax.swing.JOptionPane;
046 import javax.swing.JTextArea;
047 import de.mospace.lang.ClassLoaderProvider;
048 /* TO DO:
049 * Offer a choice of target directories:
050 * - ${java.ext.dirs}
051 * - ${user.home}/.${appname}/lib
052 * - ${user.dir}/lib
053 * - ${getRepositoryRoot(foo.bar.App.class)}/lib
054 */
055 /**
056 * Description of the Class
057 *
058 * @author ringler
059 */
060 public class ExtensionInstaller {
061 private static final Logger logger = Logger.getLogger(ExtensionInstaller.class.getPackage().getName());
062 private static String javaext = null;
063 protected final Component parent;
064 private File targetDirectory;
065 private File fallbackTargetDirectory;
066
067 /** @deprecated use
068 {@link de.mospace.lang.DefaultClassLoaderProvider#isTemporary}
069 instead. **/
070 public static boolean isTemporary(File file){
071 boolean result = false;
072 try{
073 String tempdir = System.getProperty("java.io.tmpdir");
074 tempdir = (new File(tempdir)).getCanonicalPath();
075 result = file.getCanonicalPath().startsWith(tempdir);
076 } catch (IOException ignore){
077 logger.fine(ignore.toString());
078 }
079 return result;
080 }
081
082
083 /**
084 * Constructs a new ExtensionInstaller.
085 *
086 * @param parent a parent component for dialogs opened by this installer
087 */
088 public ExtensionInstaller(Component parent) {
089 this.parent = parent;
090 }
091
092
093 /**
094 * Returns the value of the target directory property. If the target
095 * directory is not currently set it will be set by this method call as
096 * follows. If a writable extension directory can be found it is used. If no
097 * such directory exists the fallbackTargetDirectory is used if it has been
098 * set and is writable. Otherwise, the user is prompted to specify a
099 * writable extension directory.
100 *
101 * @return this installer's target directory if it is writable or null
102 * otherwise
103 */
104 public synchronized File getTargetDirectory() {
105 if (targetDirectory == null) {
106 String wed = getWritableExtensionDirectoryImpl();
107 if (wed == null) {
108 if (fallbackTargetDirectory == null) {
109 wed = getWritableExtensionDirectoryFallback();
110 } else {
111 if (!fallbackTargetDirectory.exists()) {
112 fallbackTargetDirectory.mkdirs();
113 }
114 if (canWrite(fallbackTargetDirectory)) {
115 targetDirectory = fallbackTargetDirectory;
116 }
117 }
118 }
119 if (wed != null) {
120 targetDirectory = new File(wed);
121 }
122 }
123 return (canWrite(targetDirectory)) ? targetDirectory : null;
124 }
125
126
127 /**
128 * Sets this installer's target directory.
129 *
130 * @param dir the new value for the target directory property
131 * @throws IllegalArgumentException if dir exists and is not a directory
132 * @see #getTargetDirectory()
133 */
134 public void setTargetDirectory(File dir) {
135 if (dir != null && dir.exists() && !dir.isDirectory()) {
136 throw new IllegalArgumentException(dir.getPath() + "is not a directory.");
137 }
138 targetDirectory = dir;
139 }
140
141
142 /**
143 * Sets this installer's fallback target directory.
144 *
145 * @param dir the new value for the fallback target directory
146 * @throws IllegalArgumentException if dir exists and is not a directory
147 * @see #getTargetDirectory()
148 */
149 public void setFallbackTargetDirectory(File dir) {
150 if (dir != null && dir.exists() && !dir.isDirectory()) {
151 throw new IllegalArgumentException(dir.getPath() + "is not a directory.");
152 }
153 fallbackTargetDirectory = dir;
154 }
155
156
157 /**
158 * Returns this installer's fallback target directory.
159 *
160 * @return the fallback target directory or null if it has not been set
161 * @see #getTargetDirectory()
162 */
163 public File getFallbackTargetDirectory() {
164 return fallbackTargetDirectory;
165 }
166
167
168 /**
169 * @return an existing, user-writable extension directory or <code>null</code>
170 * if the user cancelled the dialog
171 */
172 public String getWritableExtensionDirectory() {
173 synchronized (ExtensionInstaller.class) {
174 if (javaext == null) {
175 javaext = getWritableExtensionDirectoryImpl();
176 }
177 if (javaext == null) {
178 javaext = getWritableExtensionDirectoryFallback();
179 }
180 }
181 return javaext;
182 }
183
184
185 private String getWritableExtensionDirectoryFallback() {
186 File result = null;
187 String libext = System.getProperty("java.ext.dirs");
188 do {
189 result = queryFile(GLOBALS.getMessage(
190 "EXT_INST_QUERY_FILE_PROMPT",
191 libext + File.pathSeparatorChar),
192 GLOBALS.getString("EXT_INST_QUERY_FILE_TITLE"),
193 JFileChooser.DIRECTORIES_ONLY);
194 } while (result != null &&
195 !(result.isDirectory() && canWrite(result)));
196 return (result == null) ? null : result.getAbsolutePath();
197 }
198
199 private String getWritableExtensionDirectoryImpl() {
200 String result = null;
201 String libext = System.getProperty("java.ext.dirs");
202 String[] candidates = libext.split(File.pathSeparator);
203 File f;
204 for (int i = 0; i < candidates.length; i++) {
205 f = new File(candidates[i]);
206 if (canWrite(f)) {
207 result = f.getAbsolutePath();
208 break;
209 }
210 }
211 return result;
212 }
213
214
215 /**
216 * Tests whether we can write to the given file or directory.
217 *
218 * @param test the file to test
219 * @return wether we can modify or create the given file
220 */
221 public static boolean canWrite(File test) {
222 //File.canWrite is broken on NTFS
223 if(test == null) {
224 return false;
225 }
226
227 // if f does not exist we test if we can write to its parent directory
228 if(!test.exists()){
229 try {
230 return canWrite(test.getCanonicalFile().getParentFile());
231 } catch (IOException notcanonical) {
232 return false;
233 }
234 }
235
236
237 boolean canWrite = true;
238 if (test.isFile()) {
239
240 // if test exists and is a file we try if we can open it for writing
241 try {
242 FileOutputStream fos = new FileOutputStream(test, true);
243 fos.close();
244 } catch (FileNotFoundException ex) {
245 //System.out.println("Cannot write 1: "+ex.getMessage());
246 //we cannot write
247 canWrite = false;
248 } catch (IOException ex) {
249 //we did not succeed in closing fos...
250 logger.severe("IOException on file " + test);
251 logger.severe(ex.getMessage());
252 }
253
254 } else if (test.isDirectory()) {
255 // if test exists and is a directory we try if we can create a temp file
256 File tmp = null;
257 try {
258 tmp = File.createTempFile("aaa", null, test);
259 } catch (IOException ex) {
260 //we did not succeed in creating the tmp file
261 canWrite = false;
262 //System.out.println("Cannot write 2: "+ex.getMessage());
263 }
264 //clean up
265 if (tmp != null && tmp.exists()) {
266 tmp.delete();
267 }
268 } else if (!test.exists()) {
269 //f and its parent file do not exist
270 canWrite = false;
271 //System.out.println("Cannot write 3: Neither " + f.toString() +" nor its parent directory exist.");
272 }
273 return canWrite;
274 }
275
276
277 /**
278 * Asks the user to provide a File path.
279 *
280 * @param message the message text of the input dialog.
281 * @param title the title of the input dialog
282 * @param selectionmode one of JFileChooser.FILES_ONLY,
283 * FileChooser.DIRECTORIES_ONLY and JFileChooser.FILES_AND_DIRECTORIES
284 * @return A new File object or <code>null</code> if the user cancelled the
285 * dialog.
286 */
287 protected File queryFile(String message, String title, int selectionmode) {
288 Box dialogcp = Box.createVerticalBox();
289 JTextArea messageArea = new JTextArea(message, 5, 80);
290 messageArea.setOpaque(false);
291 messageArea.setEditable(false);
292 messageArea.setLineWrap(true);
293 messageArea.setWrapStyleWord(true);
294 dialogcp.add(messageArea);
295 PathInput pinz = new PathInput("", selectionmode);
296 dialogcp.add(pinz);
297 JOptionPane pane = new JOptionPane(dialogcp,
298 JOptionPane.QUESTION_MESSAGE,
299 JOptionPane.OK_CANCEL_OPTION);
300 JDialog d = pane.createDialog(parent, title);
301 d.pack();
302 d.setResizable(true);
303 d.setVisible(true);
304 d.pack();
305 return (
306 (new Integer(JOptionPane.OK_OPTION)).equals(pane.getValue())
307 )
308 ? new File(pinz.getPath())
309 : null;
310 }
311
312
313 /**
314 * Displays a warning dialog with the given title and message.
315 *
316 * @param message the warning message
317 * @param title the dialog title
318 */
319 protected void warn(String message, String title) {
320 JOptionPane.showMessageDialog(parent,
321 message, title,
322 JOptionPane.WARNING_MESSAGE);
323 }
324
325
326 /**
327 * Asks the user to answer yes or no to the given question.
328 *
329 * @param question the dialog message
330 * @param title the dialog title
331 * @return true for yes and false for no or if the user cancelled the dialog
332 */
333 protected boolean ask(String question, String title) {
334 return (JOptionPane.showConfirmDialog(parent, question, title,
335 JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE)
336 == JOptionPane.YES_OPTION);
337 }
338
339
340 /**
341 * Tests two jar files for identical contents.
342 *
343 * @param in one of the files to compare
344 * @param myOut the other jar file
345 * @return true if both files have identical contents false otherwise
346 * @throws IOException if an I/O error has occurred
347 */
348 private static boolean jarFileEquals(File in, File myOut) throws IOException {
349 /*
350 * test if both files have equal size
351 */
352 if (in.length() != myOut.length()) {
353 return false;
354 }
355
356 JarFile jin = new JarFile(in);
357 JarFile jout = new JarFile(myOut);
358
359 /*
360 * test if both jars have the same manifests
361 */
362 if (!jin.getManifest().equals(jout.getManifest())) {
363 return false;
364 }
365
366 List inEntries = Collections.list(jin.entries());
367 List outEntries = Collections.list(jout.entries());
368
369 /*
370 * test for same number of entries
371 */
372 if (inEntries.size() != outEntries.size()) {
373 return false;
374 }
375
376 /*
377 * test entry names, checksums and modification times for equality
378 */
379 Comparator comp =
380 new Comparator() {
381 public int compare(Object o1, Object o2) {
382 return ((ZipEntry) o1).getName().compareTo(
383 ((ZipEntry) o2).getName());
384 }
385 };
386 Collections.sort(inEntries, comp);
387 Collections.sort(outEntries, comp);
388
389 Iterator iin = inEntries.iterator();
390 Iterator iout = outEntries.iterator();
391 ZipEntry zin;
392 ZipEntry zout;
393
394 while (iin.hasNext()) {
395 zin = (ZipEntry) iin.next();
396 zout = (ZipEntry) iout.next();
397 if (!zin.getName().equals(zout.getName())) {
398 return false;
399 }
400 if (zin.getCrc() != zout.getCrc()) {
401 return false;
402 }
403 if (zin.getTime() != zout.getTime()) {
404 return false;
405 }
406 }
407
408 return true;
409 }
410
411
412 /**
413 * Copies in to out using nio channels.
414 * This method will not close the streams.
415 *
416 * @param in the source file input stream
417 * @param out the destination file output stream
418 * @throws IOException if an I/O error occurs
419 */
420 private void transfer(FileInputStream in, FileOutputStream out) throws IOException {
421 /*
422 * copy using nio channels
423 */
424 FileChannel sourceChannel = in.getChannel();
425 FileChannel destinationChannel = out.getChannel();
426 FileLock targetLock = destinationChannel.tryLock();
427 if (targetLock == null) {
428 throw new IOException("Cannot lock destination file.");
429 }
430 try {
431 sourceChannel.transferTo(0, sourceChannel.size(),
432 destinationChannel);
433 } finally {
434 targetLock.release();
435 }
436 }
437
438
439 /**
440 * Tests whether f is writable and asks the user to provide a different
441 * file if not.
442 *
443 * @param f the file to test
444 * @return f or the file specified by the user
445 */
446 private File checkWritable(File f) {
447 File myOut = f;
448 if (!canWrite(myOut)) {
449 String sOut = JOptionPane.showInputDialog(parent,
450 GLOBALS.getMessage("EXT_INST_WRITE_ERROR_PROMPT",
451 new Object[]{myOut.getName(), myOut.getParent()}),
452 GLOBALS.getString("EXT_INST_WRITE_ERROR_TITLE"));
453 if (sOut == null) {
454 return null;
455 }
456 if (!sOut.endsWith(".jar")) {
457 sOut += ".jar";
458 }
459 File extdir = getTargetDirectory();
460 if (extdir == null) {
461 return null;
462 }
463 myOut = new File(extdir, sOut);
464 }
465 return myOut;
466 }
467
468
469 /**
470 * Installs a Java extension.
471 *
472 * @param extjar the jar file containing the extension classes you want to
473 * install
474 * @return true if the jar file was successfully installed
475 */
476 public boolean installExtension(File extjar) {
477 return installExtension(extjar, (ClassLoaderProvider) null);
478 }
479
480 public boolean installExtension(File extjar, ClassLoaderProvider clp){
481 try {
482
483 /*
484 * Construct writable output file
485 */
486 File extdir = getTargetDirectory();
487 if (extdir == null) {
488 warn("No valid target directory.", "Installation failed");
489 return false;
490 }
491 if(!extdir.exists()){
492 extdir.mkdirs();
493 }
494 File[] jars = extdir.listFiles();
495 for(int i=0; i<jars.length; i++){
496 if(jars[i].getName().endsWith(".jar") &&
497 jarFileEquals(extjar, jars[i])){
498 return true;
499 }
500 }
501
502 File myOut = new File(extdir, extjar.getName());
503 boolean repeat = false;
504 do {
505 repeat = false;
506 if (myOut.exists()) {
507 if (jarFileEquals(extjar, myOut)) {
508 return true;
509 }
510 if (!ask(GLOBALS.getMessage("EXT_INST_OVERWRITE_PROMPT_A",
511 extjar.getName()),
512 GLOBALS.getString("EXT_INST_OVERWRITE_TITLE"))) {
513 return false;
514 }
515 File f = checkWritable(myOut);
516 if (f == null) {
517 warn("Cannot write to file " + myOut, "Installation failed");
518 return false;
519 } else if (!f.equals(myOut)) {
520 repeat = true;
521 myOut = f;
522 }
523 }
524 } while (repeat);
525
526 /*
527 * copy using nio channels
528 */
529 FileInputStream fis = new FileInputStream(extjar);
530 try {
531 FileOutputStream fos = new FileOutputStream(myOut);
532 try {
533 transfer(fis, fos);
534 } finally {
535 fos.close();
536 }
537 } finally {
538 fis.close();
539 }
540 if (myOut.exists()) {
541 /*
542 * preserve modification time
543 */
544 myOut.setLastModified(extjar.lastModified());
545 if(clp != null && myOut.getName().endsWith(".jar")){
546 clp.registerLibrary(myOut);
547 }
548 }
549 } catch (Exception ex) {
550 warn(ex.toString(), "Installation failed");
551 return false;
552 }
553 return true;
554 }
555
556
557 /**
558 * Installs a Java extension contained in a zip file.
559 *
560 * @param zip the zip archive that contains the extension jar file
561 * @param extjars the path to the extension jar file relative to the zip root
562 * @return whether the installation succeeded
563 */
564 public boolean installExtension(File zip, String extjars) {
565 return installExtension(zip, extjars, null);
566 }
567
568 public boolean installExtension(File zip, String extjars, ClassLoaderProvider clp) {
569 try {
570 ZipFile extZ = new ZipFile(zip);
571 ZipEntry extjar = extZ.getEntry(extjars);
572 if (extjar == null) {
573 return false;
574 }
575
576 /*
577 * Construct writable output file
578 */
579 File extdir = getTargetDirectory();
580 if (extdir == null) {
581 return false;
582 }
583 if(!extdir.exists()){
584 extdir.mkdirs();
585 }
586 File myOut = new File(extdir, (new File(extjars)).getName());
587 boolean repeat = false;
588 do {
589 repeat = false;
590 if (myOut.exists()) {
591 if (!ask(GLOBALS.getMessage("EXT_INST_OVERWRITE_PROMPT_B",
592 extjars),
593 GLOBALS.getString("EXT_INST_OVERWRITE_TITLE"))) {
594 return false;
595 }
596 File f = checkWritable(myOut);
597 if (f == null) {
598 return false;
599 } else if (!f.equals(myOut)) {
600 repeat = true;
601 myOut = f;
602 }
603 }
604 } while (repeat);
605
606 int count;
607 int BUFFER = 2048;
608 byte data[] = new byte[BUFFER];
609
610 InputStream is = extZ.getInputStream(extjar);
611 is = new BufferedInputStream(is);
612
613 try {
614 FileOutputStream fos = new FileOutputStream(myOut);
615 BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
616
617 try {
618 while ((count = is.read(data, 0, BUFFER)) != -1) {
619 dest.write(data, 0, count);
620 }
621 } finally {
622 dest.close();
623 }
624
625 } finally {
626 is.close();
627 }
628
629 if (myOut.exists()) {
630 /*
631 * preserve modification time
632 */
633 myOut.setLastModified(extjar.getTime());
634 if(clp != null && myOut.getName().endsWith(".jar")){
635 clp.registerLibrary(myOut);
636 }
637 }
638 } catch (IOException ex) {
639 logger.warning(ex.getMessage());
640 return false;
641 } catch (Exception ex) {
642 logger.severe(ex.toString());
643 ex.printStackTrace();
644 return false;
645 }
646 return true;
647 }
648 }