File: PluginInstaller.java

package info (click to toggle)
imagej 1.46a-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 4,248 kB
  • sloc: java: 89,778; sh: 311; xml: 51; makefile: 6
file content (101 lines) | stat: -rw-r--r-- 2,358 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package ij.io;
import ij.*;
import ij.gui.*;
import java.io.*;
import java.net.URL;
import java.net.*;

/** Intalls plugins (.jar and .class files) that have been dragged
	and dropped on the ImageJ window, or opened using 
	File/Open or the open() macro function. */
class PluginInstaller {

	boolean install(String path) {
		boolean isURL = path.startsWith("http://");
		byte[] data = null;
		String name = path;
		if (isURL) {
			URL url = null;
			try {
				url = new URL(path);
			} catch (Exception e) {
				IJ.error(""+e);
				return false;
			}
			int index = path.lastIndexOf("/");
			if (index!=-1 && index<=path.length()-1)
					name = path.substring(index+1);
			data = download(url);
		} else {
			File f = new File(path);
			name = f.getName();
			data = download(f);
		}
		if (data==null) return false;
		SaveDialog sd = new SaveDialog("Save Plugin...", Menus.getPlugInsPath(), name, null);
		String name2 = sd.getFileName();
		if (name2==null) return false;
		String dir = sd.getDirectory();
		if (!savePlugin(new File(dir,name), data))
			return false;
		Menus.updateImageJMenus();
		return true;
	}
	
	boolean savePlugin(File f, byte[] data) {
		try {
			FileOutputStream out = new FileOutputStream(f);
			out.write(data, 0, data.length);
			out.close();
		} catch (IOException e) {
			IJ.error("Plugin Installer", ""+e);
			return false;
		}
		return true;
	}

	byte[] download(URL url) {
		byte[] data;
		try {
			URLConnection uc = url.openConnection();
			int len = uc.getContentLength();
			IJ.showStatus("Downloading "+url.getFile());
			InputStream in = uc.getInputStream();
			data = new byte[len];
			int n = 0;
			while (n < len) {
				int count = in.read(data, n, len - n);
				if (count<0)
					throw new EOFException();
				n += count;
				IJ.showProgress(n, len);
			}
			in.close();
		} catch (IOException e) {
			return null;
		}
		return data;
	}
	
	byte[] download(File f) {
		if (!f.exists()) {
			IJ.error("Plugin Installer", "File not found: "+f);
			return null;
		}
		byte[] data = null;
		try {
			int len = (int)f.length();
			InputStream in = new BufferedInputStream(new FileInputStream(f));
			DataInputStream dis = new DataInputStream(in);
			data = new byte[len];
			dis.readFully(data);
			dis.close();
		}
		catch (Exception e) {
			IJ.error("Plugin Installer", ""+e);
			data = null;
		}
		return data;
	}

}