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

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

see #19251 - Java 8: use Stream

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