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

Last change on this file since 6615 was 6615, checked in by Don-vip, 10 years ago

fix compilation warnings + minor code refactorization

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