source: josm/trunk/src/org/openstreetmap/josm/actions/ExtensionFileFilter.java@ 17534

Last change on this file since 17534 was 16643, checked in by simon04, 4 years ago

see #19334 - https://errorprone.info/bugpattern/StringSplitter

  • Property svn:eol-style set to native
File size: 18.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import java.io.File;
5import java.util.ArrayList;
6import java.util.Arrays;
7import java.util.Collection;
8import java.util.Collections;
9import java.util.Comparator;
10import java.util.LinkedHashSet;
11import java.util.List;
12import java.util.Objects;
13import java.util.ServiceConfigurationError;
14import java.util.function.Predicate;
15import java.util.stream.Collectors;
16
17import javax.swing.filechooser.FileFilter;
18
19import org.openstreetmap.josm.gui.MainApplication;
20import org.openstreetmap.josm.gui.io.importexport.AllFormatsImporter;
21import org.openstreetmap.josm.gui.io.importexport.FileExporter;
22import org.openstreetmap.josm.gui.io.importexport.FileImporter;
23import org.openstreetmap.josm.gui.io.importexport.GeoJSONImporter;
24import org.openstreetmap.josm.gui.io.importexport.GpxImporter;
25import org.openstreetmap.josm.gui.io.importexport.JpgImporter;
26import org.openstreetmap.josm.gui.io.importexport.NMEAImporter;
27import org.openstreetmap.josm.gui.io.importexport.NoteImporter;
28import org.openstreetmap.josm.gui.io.importexport.OsmChangeImporter;
29import org.openstreetmap.josm.gui.io.importexport.OsmImporter;
30import org.openstreetmap.josm.gui.io.importexport.RtkLibImporter;
31import org.openstreetmap.josm.gui.io.importexport.WMSLayerImporter;
32import org.openstreetmap.josm.gui.widgets.AbstractFileChooser;
33import org.openstreetmap.josm.io.session.SessionImporter;
34import org.openstreetmap.josm.tools.Logging;
35import org.openstreetmap.josm.tools.Utils;
36
37/**
38 * A file filter that filters after the extension. Also includes a list of file
39 * filters used in JOSM.
40 * @since 32
41 */
42public class ExtensionFileFilter extends FileFilter implements java.io.FileFilter {
43
44 /**
45 * List of supported formats for import.
46 * @since 4869
47 */
48 private static final ArrayList<FileImporter> importers;
49
50 /**
51 * List of supported formats for export.
52 * @since 4869
53 */
54 private static final ArrayList<FileExporter> exporters;
55
56 // add some file types only if the relevant classes are there.
57 // this gives us the option to painlessly drop them from the .jar
58 // and build JOSM versions without support for these formats
59
60 static {
61
62 importers = new ArrayList<>();
63
64 final List<Class<? extends FileImporter>> importerNames = Arrays.asList(
65 OsmImporter.class,
66 OsmChangeImporter.class,
67 GeoJSONImporter.class,
68 GpxImporter.class,
69 NMEAImporter.class,
70 RtkLibImporter.class,
71 NoteImporter.class,
72 JpgImporter.class,
73 WMSLayerImporter.class,
74 AllFormatsImporter.class,
75 SessionImporter.class
76 );
77
78 for (final Class<? extends FileImporter> importerClass : importerNames) {
79 try {
80 FileImporter importer = importerClass.getConstructor().newInstance();
81 importers.add(importer);
82 } catch (ReflectiveOperationException e) {
83 Logging.debug(e);
84 } catch (ServiceConfigurationError e) {
85 // error seen while initializing WMSLayerImporter in plugin unit tests:
86 // -
87 // ServiceConfigurationError: javax.imageio.spi.ImageWriterSpi:
88 // Provider com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi could not be instantiated
89 // Caused by: java.lang.IllegalArgumentException: vendorName == null!
90 // at javax.imageio.spi.IIOServiceProvider.<init>(IIOServiceProvider.java:76)
91 // at javax.imageio.spi.ImageReaderWriterSpi.<init>(ImageReaderWriterSpi.java:231)
92 // at javax.imageio.spi.ImageWriterSpi.<init>(ImageWriterSpi.java:213)
93 // at com.sun.media.imageioimpl.plugins.jpeg.CLibJPEGImageWriterSpi.<init>(CLibJPEGImageWriterSpi.java:84)
94 // -
95 // This is a very strange behaviour of JAI:
96 // http://thierrywasyl.wordpress.com/2009/07/24/jai-how-to-solve-vendorname-null-exception/
97 // -
98 // that can lead to various problems, see #8583 comments
99 Logging.error(e);
100 }
101 }
102
103 exporters = new ArrayList<>();
104
105 final List<Class<? extends FileExporter>> exporterClasses = Arrays.asList(
106 org.openstreetmap.josm.gui.io.importexport.GpxExporter.class,
107 org.openstreetmap.josm.gui.io.importexport.OsmExporter.class,
108 org.openstreetmap.josm.gui.io.importexport.OsmGzipExporter.class,
109 org.openstreetmap.josm.gui.io.importexport.OsmBzip2Exporter.class,
110 org.openstreetmap.josm.gui.io.importexport.OsmXzExporter.class,
111 org.openstreetmap.josm.gui.io.importexport.GeoJSONExporter.class,
112 org.openstreetmap.josm.gui.io.importexport.WMSLayerExporter.class,
113 org.openstreetmap.josm.gui.io.importexport.NoteExporter.class,
114 org.openstreetmap.josm.gui.io.importexport.ValidatorErrorExporter.class
115 );
116
117 for (final Class<? extends FileExporter> exporterClass : exporterClasses) {
118 try {
119 FileExporter exporter = exporterClass.getConstructor().newInstance();
120 exporters.add(exporter);
121 MainApplication.getLayerManager().addAndFireActiveLayerChangeListener(exporter);
122 } catch (ReflectiveOperationException e) {
123 Logging.debug(e);
124 } catch (ServiceConfigurationError e) {
125 // see above in importers initialization
126 Logging.error(e);
127 }
128 }
129 }
130
131 private final String extensions;
132 private final String description;
133 private final String defaultExtension;
134
135 protected static Comparator<ExtensionFileFilter> comparator() {
136 AllFormatsImporter all = new AllFormatsImporter();
137 return (o1, o2) -> {
138 if (o1.getDescription().equals(all.filter.getDescription())) return 1;
139 if (o2.getDescription().equals(all.filter.getDescription())) return -1;
140 return o1.getDescription().compareTo(o2.getDescription());
141 };
142 }
143
144 /**
145 * Strategy to determine if extensions must be added to the description.
146 */
147 public enum AddArchiveExtension {
148 /** No extension is added */
149 NONE,
150 /** Only base extension is added */
151 BASE,
152 /** All extensions are added (base + archives) */
153 ALL
154 }
155
156 /**
157 * Adds a new file importer at the end of the global list. This importer will be evaluated after core ones.
158 * @param importer new file importer
159 * @since 10407
160 */
161 public static void addImporter(FileImporter importer) {
162 if (importer != null) {
163 importers.add(importer);
164 }
165 }
166
167 /**
168 * Adds a new file importer at the beginning of the global list. This importer will be evaluated before core ones.
169 * @param importer new file importer
170 * @since 10407
171 */
172 public static void addImporterFirst(FileImporter importer) {
173 if (importer != null) {
174 importers.add(0, importer);
175 }
176 }
177
178 /**
179 * Adds a new file exporter at the end of the global list. This exporter will be evaluated after core ones.
180 * @param exporter new file exporter
181 * @since 10407
182 */
183 public static void addExporter(FileExporter exporter) {
184 if (exporter != null) {
185 exporters.add(exporter);
186 }
187 }
188
189 /**
190 * Adds a new file exporter at the beginning of the global list. This exporter will be evaluated before core ones.
191 * @param exporter new file exporter
192 * @since 10407
193 */
194 public static void addExporterFirst(FileExporter exporter) {
195 if (exporter != null) {
196 exporters.add(0, exporter);
197 }
198 }
199
200 /**
201 * Returns the list of file importers.
202 * @return unmodifiable list of file importers
203 * @since 10407
204 */
205 public static List<FileImporter> getImporters() {
206 return Collections.unmodifiableList(importers);
207 }
208
209 /**
210 * Returns the list of file exporters.
211 * @return unmodifiable list of file exporters
212 * @since 10407
213 */
214 public static List<FileExporter> getExporters() {
215 return Collections.unmodifiableList(exporters);
216 }
217
218 /**
219 * Updates the {@link AllFormatsImporter} that is contained in the importers list. If
220 * you do not use the importers variable directly, you don't need to call this.
221 * <p>
222 * Updating the AllFormatsImporter is required when plugins add new importers that
223 * support new file extensions. The old AllFormatsImporter doesn't include the new
224 * extensions and thus will not display these files.
225 *
226 * @since 5131
227 */
228 public static void updateAllFormatsImporter() {
229 for (int i = 0; i < importers.size(); i++) {
230 if (importers.get(i) instanceof AllFormatsImporter) {
231 importers.set(i, new AllFormatsImporter());
232 }
233 }
234 }
235
236 /**
237 * Replies an ordered list of {@link ExtensionFileFilter}s for importing.
238 * The list is ordered according to their description, an {@link AllFormatsImporter}
239 * is append at the end.
240 *
241 * @return an ordered list of {@link ExtensionFileFilter}s for importing.
242 * @since 2029
243 */
244 public static List<ExtensionFileFilter> getImportExtensionFileFilters() {
245 updateAllFormatsImporter();
246 return importers.stream()
247 .map(importer -> importer.filter)
248 .sorted(comparator())
249 .collect(Collectors.toList());
250 }
251
252 /**
253 * Replies an ordered list of enabled {@link ExtensionFileFilter}s for exporting.
254 * The list is ordered according to their description, an {@link AllFormatsImporter}
255 * is append at the end.
256 *
257 * @return an ordered list of enabled {@link ExtensionFileFilter}s for exporting.
258 * @since 2029
259 */
260 public static List<ExtensionFileFilter> getExportExtensionFileFilters() {
261 return exporters.stream()
262 .filter(FileExporter::isEnabled)
263 .map(exporter -> exporter.filter)
264 .distinct()
265 .sorted(comparator())
266 .collect(Collectors.toList());
267 }
268
269 /**
270 * Replies the default {@link ExtensionFileFilter} for a given extension
271 *
272 * @param extension the extension
273 * @return the default {@link ExtensionFileFilter} for a given extension
274 * @since 2029
275 */
276 public static ExtensionFileFilter getDefaultImportExtensionFileFilter(String extension) {
277 if (extension == null) return new AllFormatsImporter().filter;
278 return importers.stream()
279 .filter(importer -> extension.equals(importer.filter.getDefaultExtension()))
280 .findFirst().map(importer -> importer.filter)
281 .orElseGet(() -> new AllFormatsImporter().filter);
282 }
283
284 /**
285 * Replies the default {@link ExtensionFileFilter} for a given extension
286 *
287 * @param extension the extension
288 * @return the default {@link ExtensionFileFilter} for a given extension
289 * @since 2029
290 */
291 public static ExtensionFileFilter getDefaultExportExtensionFileFilter(String extension) {
292 if (extension == null) return new AllFormatsImporter().filter;
293 for (FileExporter exporter : exporters) {
294 if (extension.equals(exporter.filter.getDefaultExtension()))
295 return exporter.filter;
296 }
297 // if extension did not match defaultExtension of any exporter,
298 // scan all supported extensions
299 File file = new File("file." + extension);
300 for (FileExporter exporter : exporters) {
301 if (exporter.filter.accept(file))
302 return exporter.filter;
303 }
304 return new AllFormatsImporter().filter;
305 }
306
307 /**
308 * Applies the choosable {@link FileFilter} to a {@link AbstractFileChooser} before using the
309 * file chooser for selecting a file for reading.
310 *
311 * @param fileChooser the file chooser
312 * @param extension the default extension
313 * @param additionalTypes matching types will additionally be added to the "file type" combobox.
314 * @since 14668 (signature)
315 */
316 public static void applyChoosableImportFileFilters(
317 AbstractFileChooser fileChooser, String extension, Predicate<ExtensionFileFilter> additionalTypes) {
318 getImportExtensionFileFilters().stream()
319 .filter(filter -> additionalTypes.test(filter) || filter.acceptName("file."+extension))
320 .forEach(fileChooser::addChoosableFileFilter);
321 fileChooser.setFileFilter(getDefaultImportExtensionFileFilter(extension));
322 }
323
324 /**
325 * Applies the choosable {@link FileFilter} to a {@link AbstractFileChooser} before using the
326 * file chooser for selecting a file for writing.
327 *
328 * @param fileChooser the file chooser
329 * @param extension the default extension
330 * @param additionalTypes matching types will additionally be added to the "file type" combobox.
331 * @since 14668 (signature)
332 */
333 public static void applyChoosableExportFileFilters(
334 AbstractFileChooser fileChooser, String extension, Predicate<ExtensionFileFilter> additionalTypes) {
335 for (ExtensionFileFilter filter: getExportExtensionFileFilters()) {
336 if (additionalTypes.test(filter) || filter.acceptName("file."+extension)) {
337 fileChooser.addChoosableFileFilter(filter);
338 }
339 }
340 fileChooser.setFileFilter(getDefaultExportExtensionFileFilter(extension));
341 }
342
343 /**
344 * Construct an extension file filter by giving the extension to check after.
345 * @param extension The comma-separated list of file extensions
346 * @param defaultExtension The default extension
347 * @param description A short textual description of the file type
348 * @since 1169
349 */
350 public ExtensionFileFilter(String extension, String defaultExtension, String description) {
351 this.extensions = extension;
352 this.defaultExtension = defaultExtension;
353 this.description = description;
354 }
355
356 /**
357 * Construct an extension file filter with the extensions supported by {@link org.openstreetmap.josm.io.Compression}
358 * automatically added to the {@code extensions}. The specified {@code extensions} will be added to the description
359 * in the form {@code old-description (*.ext1, *.ext2)}.
360 * @param extensions The comma-separated list of file extensions
361 * @param defaultExtension The default extension
362 * @param description A short textual description of the file type without supported extensions in parentheses
363 * @param addArchiveExtension Whether to also add the archive extensions to the description
364 * @param archiveExtensions List of extensions to be added
365 * @return The constructed filter
366 */
367 public static ExtensionFileFilter newFilterWithArchiveExtensions(String extensions, String defaultExtension,
368 String description, AddArchiveExtension addArchiveExtension, List<String> archiveExtensions) {
369 final Collection<String> extensionsPlusArchive = new LinkedHashSet<>();
370 final Collection<String> extensionsForDescription = new LinkedHashSet<>();
371 for (String e : extensions.split(",", -1)) {
372 extensionsPlusArchive.add(e);
373 if (addArchiveExtension != AddArchiveExtension.NONE) {
374 extensionsForDescription.add("*." + e);
375 }
376 for (String extension : archiveExtensions) {
377 extensionsPlusArchive.add(e + '.' + extension);
378 if (addArchiveExtension == AddArchiveExtension.ALL) {
379 extensionsForDescription.add("*." + e + '.' + extension);
380 }
381 }
382 }
383 return new ExtensionFileFilter(
384 String.join(",", extensionsPlusArchive),
385 defaultExtension,
386 description + (!extensionsForDescription.isEmpty()
387 ? (" (" + String.join(", ", extensionsForDescription) + ')')
388 : "")
389 );
390 }
391
392 /**
393 * Construct an extension file filter with the extensions supported by {@link org.openstreetmap.josm.io.Compression}
394 * automatically added to the {@code extensions}. The specified {@code extensions} will be added to the description
395 * in the form {@code old-description (*.ext1, *.ext2)}.
396 * @param extensions The comma-separated list of file extensions
397 * @param defaultExtension The default extension
398 * @param description A short textual description of the file type without supported extensions in parentheses
399 * @param addArchiveExtensionsToDescription Whether to also add the archive extensions to the description
400 * @return The constructed filter
401 */
402 public static ExtensionFileFilter newFilterWithArchiveExtensions(
403 String extensions, String defaultExtension, String description, boolean addArchiveExtensionsToDescription) {
404
405 List<String> archiveExtensions = Arrays.asList("gz", "bz", "bz2", "xz", "zip");
406 return newFilterWithArchiveExtensions(
407 extensions,
408 defaultExtension,
409 description,
410 addArchiveExtensionsToDescription ? AddArchiveExtension.ALL : AddArchiveExtension.BASE,
411 archiveExtensions
412 );
413 }
414
415 /**
416 * Returns true if this file filter accepts the given filename.
417 * @param filename The filename to check after
418 * @return true if this file filter accepts the given filename (i.e if this filename ends with one of the extensions)
419 * @since 1169
420 */
421 public boolean acceptName(String filename) {
422 return Utils.hasExtension(filename, extensions.split(",", -1));
423 }
424
425 @Override
426 public boolean accept(File pathname) {
427 if (pathname.isDirectory())
428 return true;
429 return acceptName(pathname.getName());
430 }
431
432 @Override
433 public String getDescription() {
434 return description;
435 }
436
437 /**
438 * Replies the comma-separated list of file extensions of this file filter.
439 * @return the comma-separated list of file extensions of this file filter, as a String
440 * @since 5131
441 */
442 public String getExtensions() {
443 return extensions;
444 }
445
446 /**
447 * Replies the default file extension of this file filter.
448 * @return the default file extension of this file filter
449 * @since 2029
450 */
451 public String getDefaultExtension() {
452 return defaultExtension;
453 }
454
455 @Override
456 public int hashCode() {
457 return Objects.hash(extensions, description, defaultExtension);
458 }
459
460 @Override
461 public boolean equals(Object obj) {
462 if (this == obj) return true;
463 if (obj == null || getClass() != obj.getClass()) return false;
464 ExtensionFileFilter that = (ExtensionFileFilter) obj;
465 return Objects.equals(extensions, that.extensions) &&
466 Objects.equals(description, that.description) &&
467 Objects.equals(defaultExtension, that.defaultExtension);
468 }
469}
Note: See TracBrowser for help on using the repository browser.