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

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

sonar - squid:S3052 - Fields should not be initialized to default values

  • 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.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.Locale;
22import java.util.Map;
23import java.util.TreeMap;
24import java.util.jar.Attributes;
25import java.util.jar.JarInputStream;
26import java.util.jar.Manifest;
27
28import javax.swing.ImageIcon;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.data.Version;
32import org.openstreetmap.josm.tools.ImageProvider;
33import org.openstreetmap.josm.tools.LanguageInfo;
34import org.openstreetmap.josm.tools.Utils;
35
36/**
37 * Encapsulate general information about a plugin. This information is available
38 * without the need of loading any class from the plugin jar file.
39 *
40 * @author imi
41 * @since 153
42 */
43public class PluginInformation {
44
45 /** The plugin jar file. */
46 public File file;
47 /** The plugin name. */
48 public String name;
49 /** The lowest JOSM version required by this plugin (from plugin list). **/
50 public int mainversion;
51 /** The lowest JOSM version required by this plugin (from locally available jar). **/
52 public int localmainversion;
53 /** The plugin class name. */
54 public String className;
55 /** Determines if the plugin is an old version loaded for incompatibility with latest JOSM (from plugin list) */
56 public boolean oldmode;
57 /** The list of required plugins, separated by ';' (from plugin list). */
58 public String requires;
59 /** The list of required plugins, separated by ';' (from locally available jar). */
60 public String localrequires;
61 /** The plugin link (for documentation). */
62 public String link;
63 /** The plugin description. */
64 public String description;
65 /** Determines if the plugin must be loaded early or not. */
66 public boolean early;
67 /** The plugin author. */
68 public String author;
69 /** The plugin stage, determining the loading sequence order of plugins. */
70 public int stage = 50;
71 /** The plugin version (from plugin list). **/
72 public String version;
73 /** The plugin version (from locally available jar). **/
74 public String localversion;
75 /** The plugin download link. */
76 public String downloadlink;
77 /** The plugin icon path inside jar. */
78 public String iconPath;
79 /** The plugin icon. */
80 public ImageIcon icon;
81 /** Plugin can be loaded at any time and not just at start. */
82 public boolean canloadatruntime;
83 /** The libraries referenced in Class-Path manifest attribute. */
84 public List<URL> libraries = new LinkedList<>();
85 /** All manifest attributes. */
86 public final Map<String, String> attr = new TreeMap<>();
87
88 private static final ImageIcon emptyIcon = new ImageIcon(new BufferedImage(24, 24, BufferedImage.TYPE_INT_ARGB));
89
90 /**
91 * Creates a plugin information object by reading the plugin information from
92 * the manifest in the plugin jar.
93 *
94 * The plugin name is derived from the file name.
95 *
96 * @param file the plugin jar file
97 * @throws PluginException if reading the manifest fails
98 */
99 public PluginInformation(File file) throws PluginException {
100 this(file, file.getName().substring(0, file.getName().length()-4));
101 }
102
103 /**
104 * Creates a plugin information object for the plugin with name {@code name}.
105 * Information about the plugin is extracted from the manifest file in the plugin jar
106 * {@code file}.
107 * @param file the plugin jar
108 * @param name the plugin name
109 * @throws PluginException if reading the manifest file fails
110 */
111 public PluginInformation(File file, String name) throws PluginException {
112 if (!PluginHandler.isValidJar(file)) {
113 throw new PluginException(name, tr("Invalid jar file ''{0}''", file));
114 }
115 this.name = name;
116 this.file = file;
117 try (
118 FileInputStream fis = new FileInputStream(file);
119 JarInputStream jar = new JarInputStream(fis)
120 ) {
121 Manifest manifest = jar.getManifest();
122 if (manifest == null)
123 throw new PluginException(name, tr("The plugin file ''{0}'' does not include a Manifest.", file.toString()));
124 scanManifest(manifest, false);
125 libraries.add(0, Utils.fileToURL(file));
126 } catch (IOException e) {
127 throw new PluginException(name, e);
128 }
129 }
130
131 /**
132 * Creates a plugin information object by reading plugin information in Manifest format
133 * from the input stream {@code manifestStream}.
134 *
135 * @param manifestStream the stream to read the manifest from
136 * @param name the plugin name
137 * @param url the download URL for the plugin
138 * @throws PluginException if the plugin information can't be read from the input stream
139 */
140 public PluginInformation(InputStream manifestStream, String name, String url) throws PluginException {
141 this.name = name;
142 try {
143 Manifest manifest = new Manifest();
144 manifest.read(manifestStream);
145 if (url != null) {
146 downloadlink = url;
147 }
148 scanManifest(manifest, url != null);
149 } catch (IOException e) {
150 throw new PluginException(name, e);
151 }
152 }
153
154 /**
155 * Updates the plugin information of this plugin information object with the
156 * plugin information in a plugin information object retrieved from a plugin
157 * update site.
158 *
159 * @param other the plugin information object retrieved from the update site
160 */
161 public void updateFromPluginSite(PluginInformation other) {
162 this.mainversion = other.mainversion;
163 this.className = other.className;
164 this.requires = other.requires;
165 this.link = other.link;
166 this.description = other.description;
167 this.early = other.early;
168 this.author = other.author;
169 this.stage = other.stage;
170 this.version = other.version;
171 this.downloadlink = other.downloadlink;
172 this.icon = other.icon;
173 this.iconPath = other.iconPath;
174 this.canloadatruntime = other.canloadatruntime;
175 this.libraries = other.libraries;
176 this.attr.clear();
177 this.attr.putAll(other.attr);
178 }
179
180 /**
181 * Updates the plugin information of this plugin information object with the
182 * plugin information in a plugin information object retrieved from a plugin
183 * jar.
184 *
185 * @param other the plugin information object retrieved from the jar file
186 * @since 5601
187 */
188 public void updateFromJar(PluginInformation other) {
189 updateLocalInfo(other);
190 if (other.icon != null) {
191 this.icon = other.icon;
192 }
193 this.early = other.early;
194 this.className = other.className;
195 this.canloadatruntime = other.canloadatruntime;
196 this.libraries = other.libraries;
197 this.stage = other.stage;
198 }
199
200 private void scanManifest(Manifest manifest, boolean oldcheck) {
201 String lang = LanguageInfo.getLanguageCodeManifest();
202 Attributes attr = manifest.getMainAttributes();
203 className = attr.getValue("Plugin-Class");
204 String s = attr.getValue(lang+"Plugin-Link");
205 if (s == null) {
206 s = attr.getValue("Plugin-Link");
207 }
208 if (s != null) {
209 try {
210 new URL(s);
211 } catch (MalformedURLException e) {
212 Main.info(tr("Invalid URL ''{0}'' in plugin {1}", s, name));
213 s = null;
214 }
215 }
216 link = s;
217 requires = attr.getValue("Plugin-Requires");
218 s = attr.getValue(lang+"Plugin-Description");
219 if (s == null) {
220 s = attr.getValue("Plugin-Description");
221 if (s != null) {
222 try {
223 s = tr(s);
224 } catch (IllegalArgumentException e) {
225 Main.info(tr("Invalid plugin description ''{0}'' in plugin {1}", s, name));
226 }
227 }
228 } else {
229 s = MessageFormat.format(s, (Object[]) null);
230 }
231 description = s;
232 early = Boolean.parseBoolean(attr.getValue("Plugin-Early"));
233 String stageStr = attr.getValue("Plugin-Stage");
234 stage = stageStr == null ? 50 : Integer.parseInt(stageStr);
235 version = attr.getValue("Plugin-Version");
236 s = attr.getValue("Plugin-Mainversion");
237 if (s != null) {
238 try {
239 mainversion = Integer.parseInt(s);
240 } catch (NumberFormatException e) {
241 Main.warn(tr("Invalid plugin main version ''{0}'' in plugin {1}", s, name));
242 }
243 } else {
244 Main.warn(tr("Missing plugin main version in plugin {0}", name));
245 }
246 author = attr.getValue("Author");
247 iconPath = attr.getValue("Plugin-Icon");
248 if (iconPath != null) {
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(128);
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>").append(tr("<b>Plugin provided by an external source:</b> {0}", downloadlink)).append("</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(Locale.ENGLISH).contains(filter.toLowerCase(Locale.ENGLISH));
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 Plugin 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.