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

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

fix #8202 - Robustness in plugin description parsing

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