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

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

Consecutively calls to StringBuffer/StringBuilder .append should reuse the target object

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