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

Last change on this file since 12119 was 11893, checked in by Don-vip, 7 years ago

sonar - squid:S1126 - Return of boolean expressions should not be wrapped into an "if-then-else" statement

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