source: josm/trunk/src/org/openstreetmap/josm/plugins/PluginInformation.java@ 4159

Last change on this file since 4159 was 4145, checked in by stoecker, 13 years ago

see #6213 - do more file closes hopefully fixing some update problems under windows

  • Property svn:eol-style set to native
File size: 16.6 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.plugins;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Image;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.lang.reflect.Constructor;
12import java.lang.reflect.InvocationTargetException;
13import java.net.MalformedURLException;
14import java.net.URL;
15import java.util.ArrayList;
16import java.util.Collection;
17import java.util.LinkedList;
18import java.util.List;
19import java.util.Map;
20import java.util.TreeMap;
21import java.util.jar.Attributes;
22import java.util.jar.JarInputStream;
23import java.util.jar.Manifest;
24import javax.swing.ImageIcon;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.data.Version;
28import org.openstreetmap.josm.tools.ImageProvider;
29import org.openstreetmap.josm.tools.LanguageInfo;
30
31/**
32 * Encapsulate general information about a plugin. This information is available
33 * without the need of loading any class from the plugin jar file.
34 *
35 * @author imi
36 */
37public class PluginInformation {
38 public File file = null;
39 public String name = null;
40 public int mainversion = 0;
41 public String className = null;
42 public boolean oldmode = false;
43 public String requires = null;
44 public String link = null;
45 public String description = null;
46 public boolean early = false;
47 public String author = null;
48 public int stage = 50;
49 public String version = null;
50 public String localversion = null;
51 public String downloadlink = null;
52 public String iconPath;
53 public ImageIcon icon;
54 public List<URL> libraries = new LinkedList<URL>();
55 public final Map<String, String> attr = new TreeMap<String, String>();
56
57 /**
58 * Creates a plugin information object by reading the plugin information from
59 * the manifest in the plugin jar.
60 *
61 * The plugin name is derived from the file name.
62 *
63 * @param file the plugin jar file
64 * @throws PluginException if reading the manifest fails
65 */
66 public PluginInformation(File file) throws PluginException{
67 this(file, file.getName().substring(0, file.getName().length()-4));
68 }
69
70 /**
71 * Creates a plugin information object for the plugin with name {@code name}.
72 * Information about the plugin is extracted from the maifest file in the the plugin jar
73 * {@code file}.
74 * @param file the plugin jar
75 * @param name the plugin name
76 * @throws PluginException thrown if reading the manifest file fails
77 */
78 public PluginInformation(File file, String name) throws PluginException{
79 this.name = name;
80 this.file = file;
81 FileInputStream fis = null;
82 JarInputStream jar = null;
83 try {
84 fis = new FileInputStream(file);
85 jar = new JarInputStream(fis);
86 Manifest manifest = jar.getManifest();
87 if (manifest == null)
88 throw new PluginException(name, tr("The plugin file ''{0}'' does not include a Manifest.", file.toString()));
89 scanManifest(manifest, false);
90 libraries.add(0, fileToURL(file));
91 } catch (IOException e) {
92 throw new PluginException(name, e);
93 } finally {
94 if (jar != null) {
95 try {
96 jar.close();
97 } catch(IOException e) { /* ignore */ }
98 }
99 if (fis != null) {
100 try {
101 fis.close();
102 } catch(IOException e) { /* ignore */ }
103 }
104 }
105 }
106
107 /**
108 * Creates a plugin information object by reading plugin information in Manifest format
109 * from the input stream {@code manifestStream}.
110 *
111 * @param manifestStream the stream to read the manifest from
112 * @param name the plugin name
113 * @param url the download URL for the plugin
114 * @throws PluginException thrown if the plugin information can't be read from the input stream
115 */
116 public PluginInformation(InputStream manifestStream, String name, String url) throws PluginException {
117 this.name = name;
118 try {
119 Manifest manifest = new Manifest();
120 manifest.read(manifestStream);
121 if(url != null) {
122 downloadlink = url;
123 }
124 scanManifest(manifest, url != null);
125 } catch (IOException e) {
126 throw new PluginException(name, e);
127 }
128 }
129
130 /**
131 * Updates the plugin information of this plugin information object with the
132 * plugin information in a plugin information object retrieved from a plugin
133 * update site.
134 *
135 * @param other the plugin information object retrieved from the update
136 * site
137 */
138 public void updateFromPluginSite(PluginInformation other) {
139 this.mainversion = other.mainversion;
140 this.className = other.className;
141 this.requires = other.requires;
142 this.link = other.link;
143 this.description = other.description;
144 this.early = other.early;
145 this.author = other.author;
146 this.stage = other.stage;
147 this.version = other.version;
148 this.downloadlink = other.downloadlink;
149 this.icon = other.icon;
150 this.iconPath = other.iconPath;
151 this.libraries = other.libraries;
152 this.attr.clear();
153 this.attr.putAll(other.attr);
154 }
155
156 private void scanManifest(Manifest manifest, boolean oldcheck){
157 String lang = LanguageInfo.getLanguageCodeManifest();
158 Attributes attr = manifest.getMainAttributes();
159 className = attr.getValue("Plugin-Class");
160 String s = attr.getValue(lang+"Plugin-Link");
161 if(s == null) {
162 s = attr.getValue("Plugin-Link");
163 }
164 if(s != null) {
165 try {
166 URL url = new URL(s);
167 } catch (MalformedURLException e) {
168 System.out.println(tr("Invalid URL ''{0}'' in plugin {1}", s, name));
169 s = null;
170 }
171 }
172 link = s;
173 requires = attr.getValue("Plugin-Requires");
174 s = attr.getValue(lang+"Plugin-Description");
175 if(s == null)
176 {
177 s = attr.getValue("Plugin-Description");
178 if(s != null) {
179 s = tr(s);
180 }
181 }
182 description = s;
183 early = Boolean.parseBoolean(attr.getValue("Plugin-Early"));
184 String stageStr = attr.getValue("Plugin-Stage");
185 stage = stageStr == null ? 50 : Integer.parseInt(stageStr);
186 version = attr.getValue("Plugin-Version");
187 try { mainversion = Integer.parseInt(attr.getValue("Plugin-Mainversion")); }
188 catch(NumberFormatException e) {}
189 author = attr.getValue("Author");
190 iconPath = attr.getValue("Plugin-Icon");
191 if (iconPath != null && file != null) {
192 // extract icon from the plugin jar file
193 icon = ImageProvider.getIfAvailable(null, null, null, iconPath, file);
194 }
195 if(oldcheck && mainversion > Version.getInstance().getVersion())
196 {
197 int myv = Version.getInstance().getVersion();
198 for(Map.Entry<Object, Object> entry : attr.entrySet())
199 {
200 try {
201 String key = ((Attributes.Name)entry.getKey()).toString();
202 if(key.endsWith("_Plugin-Url"))
203 {
204 int mv = Integer.parseInt(key.substring(0,key.length()-11));
205 if(mv <= myv && (mv > mainversion || mainversion > myv))
206 {
207 String v = (String)entry.getValue();
208 int i = v.indexOf(";");
209 if(i > 0)
210 {
211 downloadlink = v.substring(i+1);
212 mainversion = mv;
213 version = v.substring(0,i);
214 oldmode = true;
215 }
216 }
217 }
218 }
219 catch(Exception e) { e.printStackTrace(); }
220 }
221 }
222
223 String classPath = attr.getValue(Attributes.Name.CLASS_PATH);
224 if (classPath != null) {
225 for (String entry : classPath.split(" ")) {
226 File entryFile;
227 if (new File(entry).isAbsolute() || file == null) {
228 entryFile = new File(entry);
229 } else {
230 entryFile = new File(file.getParent(), entry);
231 }
232
233 libraries.add(fileToURL(entryFile));
234 }
235 }
236 for (Object o : attr.keySet()) {
237 this.attr.put(o.toString(), attr.getValue(o.toString()));
238 }
239 }
240
241 /**
242 * Replies the description as HTML document, including a link to a web page with
243 * more information, provided such a link is available.
244 *
245 * @return the description as HTML document
246 */
247 public String getDescriptionAsHtml() {
248 StringBuilder sb = new StringBuilder();
249 sb.append("<html><body>");
250 sb.append(description == null ? tr("no description available") : description);
251 if (link != null) {
252 sb.append(" <a href=\"").append(link).append("\">").append(tr("More info...")).append("</a>");
253 }
254 if (downloadlink != null && !downloadlink.startsWith("http://svn.openstreetmap.org/applications/editors/josm/dist/")) {
255 sb.append("<p>&nbsp;</p><p>"+tr("<b>Plugin provided by an external source:</b> {0}", downloadlink)+"</p>");
256 }
257 sb.append("</body></html>");
258 return sb.toString();
259 }
260
261 /**
262 * Load and instantiate the plugin
263 *
264 * @param the plugin class
265 * @return the instantiated and initialized plugin
266 */
267 public PluginProxy load(Class<?> klass) throws PluginException{
268 try {
269 Constructor<?> c = klass.getConstructor(PluginInformation.class);
270 Object plugin = c.newInstance(this);
271 return new PluginProxy(plugin, this);
272 } catch(NoSuchMethodException e) {
273 throw new PluginException(name, e);
274 } catch(IllegalAccessException e) {
275 throw new PluginException(name, e);
276 } catch (InstantiationException e) {
277 throw new PluginException(name, e);
278 } catch(InvocationTargetException e) {
279 throw new PluginException(name, e);
280 }
281 }
282
283 /**
284 * Load the class of the plugin
285 *
286 * @param classLoader the class loader to use
287 * @return the loaded class
288 */
289 public Class<?> loadClass(ClassLoader classLoader) throws PluginException {
290 if (className == null)
291 return null;
292 try{
293 Class<?> realClass = Class.forName(className, true, classLoader);
294 return realClass;
295 } catch (ClassNotFoundException e) {
296 throw new PluginException(name, e);
297 } catch(ClassCastException e) {
298 throw new PluginException(name, e);
299 }
300 }
301
302 public static URL fileToURL(File f) {
303 try {
304 return f.toURI().toURL();
305 } catch (MalformedURLException ex) {
306 return null;
307 }
308 }
309
310 /**
311 * Try to find a plugin after some criterias. Extract the plugin-information
312 * from the plugin and return it. The plugin is searched in the following way:
313 *
314 *<li>first look after an MANIFEST.MF in the package org.openstreetmap.josm.plugins.<plugin name>
315 * (After removing all fancy characters from the plugin name).
316 * If found, the plugin is loaded using the bootstrap classloader.
317 *<li>If not found, look for a jar file in the user specific plugin directory
318 * (~/.josm/plugins/<plugin name>.jar)
319 *<li>If not found and the environment variable JOSM_RESOURCES + "/plugins/" exist, look there.
320 *<li>Try for the java property josm.resources + "/plugins/" (set via java -Djosm.plugins.path=...)
321 *<li>If the environment variable ALLUSERSPROFILE and APPDATA exist, look in
322 * ALLUSERSPROFILE/<the last stuff from APPDATA>/JOSM/plugins.
323 * (*sic* There is no easy way under Windows to get the All User's application
324 * directory)
325 *<li>Finally, look in some typical unix paths:<ul>
326 * <li>/usr/local/share/josm/plugins/
327 * <li>/usr/local/lib/josm/plugins/
328 * <li>/usr/share/josm/plugins/
329 * <li>/usr/lib/josm/plugins/
330 *
331 * If a plugin class or jar file is found earlier in the list but seem not to
332 * be working, an PluginException is thrown rather than continuing the search.
333 * This is so JOSM can detect broken user-provided plugins and do not go silently
334 * ignore them.
335 *
336 * The plugin is not initialized. If the plugin is a .jar file, it is not loaded
337 * (only the manifest is extracted). In the classloader-case, the class is
338 * bootstraped (e.g. static {} - declarations will run. However, nothing else is done.
339 *
340 * @param pluginName The name of the plugin (in all lowercase). E.g. "lang-de"
341 * @return Information about the plugin or <code>null</code>, if the plugin
342 * was nowhere to be found.
343 * @throws PluginException In case of broken plugins.
344 */
345 public static PluginInformation findPlugin(String pluginName) throws PluginException {
346 String name = pluginName;
347 name = name.replaceAll("[-. ]", "");
348 InputStream manifestStream = PluginInformation.class.getResourceAsStream("/org/openstreetmap/josm/plugins/"+name+"/MANIFEST.MF");
349 if (manifestStream != null)
350 return new PluginInformation(manifestStream, pluginName, null);
351
352 Collection<String> locations = getPluginLocations();
353
354 for (String s : locations) {
355 File pluginFile = new File(s, pluginName + ".jar");
356 if (pluginFile.exists()) {
357 PluginInformation info = new PluginInformation(pluginFile);
358 return info;
359 }
360 }
361 return null;
362 }
363
364 public static Collection<String> getPluginLocations() {
365 Collection<String> locations = Main.pref.getAllPossiblePreferenceDirs();
366 Collection<String> all = new ArrayList<String>(locations.size());
367 for (String s : locations) {
368 all.add(s+"plugins");
369 }
370 return all;
371 }
372
373 /**
374 * Replies true if the plugin with the given information is most likely outdated with
375 * respect to the referenceVersion.
376 *
377 * @param referenceVersion the reference version. Can be null if we don't know a
378 * reference version
379 *
380 * @return true, if the plugin needs to be updated; false, otherweise
381 */
382 public boolean isUpdateRequired(String referenceVersion) {
383 if (this.downloadlink == null) return false;
384 if (this.version == null && referenceVersion!= null)
385 return true;
386 if (this.version != null && !this.version.equals(referenceVersion))
387 return true;
388 return false;
389 }
390
391 /**
392 * Replies true if this this plugin should be updated/downloaded because either
393 * it is not available locally (its local version is null) or its local version is
394 * older than the available version on the server.
395 *
396 * @return true if the plugin should be updated
397 */
398 public boolean isUpdateRequired() {
399 if (this.downloadlink == null) return false;
400 if (this.localversion == null) return true;
401 return isUpdateRequired(this.localversion);
402 }
403
404 protected boolean matches(String filter, String value) {
405 if (filter == null) return true;
406 if (value == null) return false;
407 return value.toLowerCase().contains(filter.toLowerCase());
408 }
409
410 /**
411 * Replies true if either the name, the description, or the version match (case insensitive)
412 * one of the words in filter. Replies true if filter is null.
413 *
414 * @param filter the filter expression
415 * @return true if this plugin info matches with the filter
416 */
417 public boolean matches(String filter) {
418 if (filter == null) return true;
419 String words[] = filter.split("\\s+");
420 for (String word: words) {
421 if (matches(word, name)
422 || matches(word, description)
423 || matches(word, version)
424 || matches(word, localversion))
425 return true;
426 }
427 return false;
428 }
429
430 /**
431 * Replies the name of the plugin
432 */
433 public String getName() {
434 return name;
435 }
436
437 /**
438 * Sets the name
439 * @param name
440 */
441 public void setName(String name) {
442 this.name = name;
443 }
444
445 public ImageIcon getScaledIcon() {
446 if (icon == null)
447 return null;
448 return new ImageIcon(icon.getImage().getScaledInstance(24, 24, Image.SCALE_SMOOTH));
449 }
450}
Note: See TracBrowser for help on using the repository browser.