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

Last change on this file since 10308 was 10294, checked in by Don-vip, 8 years ago

sonar - squid:S1848 - refactor URL checks

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