001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.io.importexport; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.io.File; 007import java.io.IOException; 008import java.io.InputStream; 009import java.util.List; 010 011import org.openstreetmap.josm.actions.ExtensionFileFilter; 012import org.openstreetmap.josm.data.notes.Note; 013import org.openstreetmap.josm.gui.MainApplication; 014import org.openstreetmap.josm.gui.layer.NoteLayer; 015import org.openstreetmap.josm.gui.progress.ProgressMonitor; 016import org.openstreetmap.josm.io.Compression; 017import org.openstreetmap.josm.io.NoteReader; 018import org.openstreetmap.josm.tools.Logging; 019import org.xml.sax.SAXException; 020 021/** 022 * File importer that reads note dump files (*.osn, .osn.gz, .osn.xz and .osn.bz2) 023 * @since 7538 024 */ 025public class NoteImporter extends FileImporter { 026 027 /** 028 * The Notes file filter (*.osn files). 029 * @since 13114 030 */ 031 public static final ExtensionFileFilter FILE_FILTER = ExtensionFileFilter.newFilterWithArchiveExtensions( 032 "osn", "osn", tr("Note Files"), true); 033 034 /** Create an importer for note dump files */ 035 public NoteImporter() { 036 super(FILE_FILTER); 037 } 038 039 @Override 040 public void importData(final File file, ProgressMonitor progressMonitor) throws IOException { 041 if (Logging.isDebugEnabled()) { 042 Logging.debug("importing notes file {0}", file.getAbsolutePath()); 043 } 044 try (InputStream is = Compression.getUncompressedFileInputStream(file)) { 045 final NoteLayer layer = loadLayer(is, file, file.getName(), progressMonitor); 046 if (!MainApplication.getLayerManager().containsLayer(layer)) { 047 MainApplication.getLayerManager().addLayer(layer); 048 } 049 } catch (SAXException e) { 050 Logging.error("error opening up notes file"); 051 Logging.error(e); 052 throw new IOException(e.getMessage(), e); 053 } 054 } 055 056 /** 057 * Load note layer from InputStream. 058 * @param in input stream 059 * @param associatedFile filename of data (can be <code>null</code> if the stream does not come from a file) 060 * @param layerName name of generated layer 061 * @param progressMonitor handler for progress monitoring and canceling 062 * @return note layer 063 * @throws IOException if any I/O error occurs 064 * @throws SAXException if any SAX error occurs 065 * @since 9746 066 */ 067 public NoteLayer loadLayer(InputStream in, final File associatedFile, final String layerName, ProgressMonitor progressMonitor) 068 throws SAXException, IOException { 069 final List<Note> fileNotes = new NoteReader(in).parse(); 070 NoteLayer layer = MainApplication.getLayerManager().getNoteLayer(); 071 if (layer != null) { 072 layer.getNoteData().addNotes(fileNotes); 073 } else { 074 layer = new NoteLayer(fileNotes, associatedFile != null ? associatedFile.getName() : tr("Notes")); 075 } 076 return layer; 077 } 078}