Changeset 7248 in josm


Ignore:
Timestamp:
2014-06-14T12:40:50+02:00 (10 years ago)
Author:
bastiK
Message:

reworked MirroredInputStream (renamed to CachedFile):

  • no more awkwardly open and close InputStream if you just want the underlying file (e.g. to get file inside zip file)
  • make it easier to add configuration parameters, without having endless list of parameters for the constructor (Factory style, similar to ImageProvider)

breaks plugins; see #10139

Location:
trunk/src/org/openstreetmap/josm
Files:
19 edited
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/Preferences.java

    r7140 r7248  
    5151import org.openstreetmap.josm.Main;
    5252import org.openstreetmap.josm.data.preferences.ColorProperty;
    53 import org.openstreetmap.josm.io.MirroredInputStream;
     53import org.openstreetmap.josm.io.CachedFile;
    5454import org.openstreetmap.josm.io.XmlWriter;
    5555import org.openstreetmap.josm.tools.CheckParameterUtil;
     
    13901390    public void validateXML(Reader in) throws Exception {
    13911391        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    1392         try (InputStream xsdStream = new MirroredInputStream("resource://data/preferences.xsd")) {
     1392        try (InputStream xsdStream = new CachedFile("resource://data/preferences.xsd").getInputStream()) {
    13931393            Schema schema = factory.newSchema(new StreamSource(xsdStream));
    13941394            Validator validator = schema.newValidator();
  • trunk/src/org/openstreetmap/josm/data/imagery/ImageryLayerInfo.java

    r7203 r7248  
    1616import org.openstreetmap.josm.Main;
    1717import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryPreferenceEntry;
    18 import org.openstreetmap.josm.io.MirroredInputStream;
     18import org.openstreetmap.josm.io.CachedFile;
    1919import org.openstreetmap.josm.io.imagery.ImageryReader;
    2020import org.xml.sax.SAXException;
     
    7878        for (String source : Main.pref.getCollection("imagery.layers.sites", Arrays.asList(DEFAULT_LAYER_SITES))) {
    7979            if (clearCache) {
    80                 MirroredInputStream.cleanup(source);
     80                CachedFile.cleanup(source);
    8181            }
    8282            try {
  • trunk/src/org/openstreetmap/josm/data/projection/Projections.java

    r7082 r7248  
    3232import org.openstreetmap.josm.gui.preferences.projection.ProjectionChoice;
    3333import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
    34 import org.openstreetmap.josm.io.MirroredInputStream;
     34import org.openstreetmap.josm.io.CachedFile;
    3535import org.openstreetmap.josm.tools.Pair;
    3636
     
    133133        Pattern epsgPattern = Pattern.compile("<(\\d+)>(.*)<>");
    134134        try (
    135             InputStream in = new MirroredInputStream("resource://data/projection/epsg");
     135            InputStream in = new CachedFile("resource://data/projection/epsg").getInputStream();
    136136            BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
    137137        ) {
  • trunk/src/org/openstreetmap/josm/data/projection/datum/NTV2GridShiftFileWrapper.java

    r7033 r7248  
    44import java.io.InputStream;
    55
    6 import org.openstreetmap.josm.io.MirroredInputStream;
     6import org.openstreetmap.josm.io.CachedFile;
    77
    88/**
     
    4848    public NTV2GridShiftFile getShiftFile() {
    4949        if (instance == null) {
    50             try (InputStream is = new MirroredInputStream(gridFileName)) {
     50            try (InputStream is = new CachedFile(gridFileName).getInputStream()) {
    5151                instance = new NTV2GridShiftFile();
    5252                instance.loadGridShiftFile(is, false);
  • trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java

    r7240 r7248  
    66import java.io.BufferedReader;
    77import java.io.IOException;
     8import java.io.InputStream;
    89import java.io.Reader;
    910import java.util.ArrayList;
     
    4546import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
    4647import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
    47 import org.openstreetmap.josm.io.MirroredInputStream;
     48import org.openstreetmap.josm.io.CachedFile;
    4849import org.openstreetmap.josm.io.UTFInputStreamReader;
    4950import org.openstreetmap.josm.tools.CheckParameterUtil;
     
    533534                    Main.info(tr("Adding {0} to tag checker", i));
    534535                }
    535                 try (MirroredInputStream s = new MirroredInputStream(i)) {
     536                try (InputStream s = new CachedFile(i).getInputStream()) {
    536537                    addMapCSS(new BufferedReader(UTFInputStreamReader.create(s)));
    537538                }
  • trunk/src/org/openstreetmap/josm/data/validation/tests/OpeningHourTest.java

    r7082 r7248  
    2424import org.openstreetmap.josm.data.validation.Test;
    2525import org.openstreetmap.josm.data.validation.TestError;
    26 import org.openstreetmap.josm.io.MirroredInputStream;
     26import org.openstreetmap.josm.io.CachedFile;
    2727
    2828/**
     
    5353        if (ENGINE != null) {
    5454            try (Reader reader = new InputStreamReader(
    55                     new MirroredInputStream("resource://data/validator/opening_hours.js"), StandardCharsets.UTF_8)) {
     55                    new CachedFile("resource://data/validator/opening_hours.js").getInputStream(), StandardCharsets.UTF_8)) {
    5656                ENGINE.eval(reader);
    5757                // fake country/state to not get errors on holidays
  • trunk/src/org/openstreetmap/josm/data/validation/tests/TagChecker.java

    r7100 r7248  
    1111import java.io.FileNotFoundException;
    1212import java.io.IOException;
     13import java.io.InputStream;
    1314import java.text.MessageFormat;
    1415import java.util.ArrayList;
     
    5051import org.openstreetmap.josm.gui.tagging.TaggingPresets;
    5152import org.openstreetmap.josm.gui.widgets.EditableList;
    52 import org.openstreetmap.josm.io.MirroredInputStream;
     53import org.openstreetmap.josm.io.CachedFile;
    5354import org.openstreetmap.josm.io.UTFInputStreamReader;
    5455import org.openstreetmap.josm.tools.GBC;
     
    165166        for (String source : Main.pref.getCollection(PREF_SOURCES, DEFAULT_SOURCES)) {
    166167            try (
    167                 MirroredInputStream s = new MirroredInputStream(source);
     168                InputStream s = new CachedFile(source).getInputStream();
    168169                BufferedReader reader = new BufferedReader(UTFInputStreamReader.create(s));
    169170            ) {
  • trunk/src/org/openstreetmap/josm/gui/mappaint/MapPaintStyles.java

    r7198 r7248  
    3030import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference.MapPaintPrefHelper;
    3131import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    32 import org.openstreetmap.josm.io.MirroredInputStream;
     32import org.openstreetmap.josm.io.CachedFile;
    3333import org.openstreetmap.josm.tools.ImageProvider;
    3434import org.openstreetmap.josm.tools.Utils;
     
    228228
    229229    private static StyleSource fromSourceEntry(SourceEntry entry) {
    230         MirroredInputStream in = null;
     230        CachedFile cf = null;
    231231        try {
    232232            Set<String> mimes = new HashSet<>();
    233233            mimes.addAll(Arrays.asList(XmlStyleSource.XML_STYLE_MIME_TYPES.split(", ")));
    234234            mimes.addAll(Arrays.asList(MapCSSStyleSource.MAPCSS_STYLE_MIME_TYPES.split(", ")));
    235             in = new MirroredInputStream(entry.url, null, Utils.join(", ", mimes));
    236             String zipEntryPath = in.findZipEntryPath("mapcss", "style");
     235            cf = new CachedFile(entry.url).setHttpAccept(Utils.join(", ", mimes));
     236            String zipEntryPath = cf.findZipEntryPath("mapcss", "style");
    237237            if (zipEntryPath != null) {
    238238                entry.isZip = true;
     
    240240                return new MapCSSStyleSource(entry);
    241241            }
    242             zipEntryPath = in.findZipEntryPath("xml", "style");
     242            zipEntryPath = cf.findZipEntryPath("xml", "style");
    243243            if (zipEntryPath != null)
    244244                return new XmlStyleSource(entry);
     
    248248                return new XmlStyleSource(entry);
    249249            else {
    250                 try (InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)) {
     250                try (InputStreamReader reader = new InputStreamReader(cf.getInputStream(), StandardCharsets.UTF_8)) {
    251251                    WHILE: while (true) {
    252252                        int c = reader.read();
     
    272272            Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", entry.url, e.toString()));
    273273            Main.error(e);
    274         } finally {
    275             Utils.close(in);
    276274        }
    277275        return null;
  • trunk/src/org/openstreetmap/josm/gui/mappaint/StyleSource.java

    r7185 r7248  
    1818import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference;
    1919import org.openstreetmap.josm.gui.preferences.SourceEntry;
    20 import org.openstreetmap.josm.io.MirroredInputStream;
     20import org.openstreetmap.josm.io.CachedFile;
    2121import org.openstreetmap.josm.tools.ImageProvider;
    2222import org.openstreetmap.josm.tools.Utils;
     
    8282
    8383    /**
    84      * Returns a new {@code MirroredInputStream} to the local file containing style source (can be a text file or an archive).
    85      * @return A new {@code MirroredInputStream} to the local file containing style source
     84     * Returns a new {@code CachedFile} to the local file containing style source (can be a text file or an archive).
     85     * @return A new {@code CachedFile} to the local file containing style source
    8686     * @throws IOException if any I/O error occurs.
    8787     * @since 7081
    8888     */
    89     public abstract MirroredInputStream getMirroredInputStream() throws IOException;
     89    public abstract CachedFile getCachedFile() throws IOException;
    9090
    9191    /**
  • trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java

    r7200 r7248  
    4242import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.TokenMgrError;
    4343import org.openstreetmap.josm.gui.preferences.SourceEntry;
    44 import org.openstreetmap.josm.io.MirroredInputStream;
     44import org.openstreetmap.josm.io.CachedFile;
    4545import org.openstreetmap.josm.tools.CheckParameterUtil;
    4646import org.openstreetmap.josm.tools.LanguageInfo;
     
    275275            return new ByteArrayInputStream(css.getBytes(StandardCharsets.UTF_8));
    276276        }
    277         MirroredInputStream in = getMirroredInputStream();
     277        CachedFile cf = getCachedFile();
    278278        if (isZip) {
    279             File file = in.getFile();
    280             Utils.close(in);
     279            File file = cf.getFile();
    281280            zipFile = new ZipFile(file, StandardCharsets.UTF_8);
    282281            zipIcons = file;
     
    286285            zipFile = null;
    287286            zipIcons = null;
    288             return in;
    289         }
    290     }
    291 
    292     @Override
    293     public MirroredInputStream getMirroredInputStream() throws IOException {
    294         return new MirroredInputStream(url, null, MAPCSS_STYLE_MIME_TYPES);
     287            return cf.getInputStream();
     288        }
     289    }
     290
     291    @Override
     292    public CachedFile getCachedFile() throws IOException {
     293        return new CachedFile(url).setHttpAccept(MAPCSS_STYLE_MIME_TYPES);
    295294    }
    296295
  • trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java

    r7083 r7248  
    2929import org.openstreetmap.josm.gui.mappaint.StyleSource;
    3030import org.openstreetmap.josm.gui.preferences.SourceEntry;
    31 import org.openstreetmap.josm.io.MirroredInputStream;
     31import org.openstreetmap.josm.io.CachedFile;
    3232import org.openstreetmap.josm.tools.Utils;
    3333import org.openstreetmap.josm.tools.XmlObjectParser;
     
    104104    @Override
    105105    public InputStream getSourceInputStream() throws IOException {
    106         MirroredInputStream in = getMirroredInputStream();
    107         InputStream zip = in.findZipEntryInputStream("xml", "style");
     106        CachedFile cf = getCachedFile();
     107        InputStream zip = cf.findZipEntryInputStream("xml", "style");
    108108        if (zip != null) {
    109             zipIcons = in.getFile();
     109            zipIcons = cf.getFile();
    110110            return zip;
    111111        } else {
    112112            zipIcons = null;
    113             return in;
    114         }
    115     }
    116 
    117     @Override
    118     public MirroredInputStream getMirroredInputStream() throws IOException {
    119         return new MirroredInputStream(url, null, XML_STYLE_MIME_TYPES);
     113            return cf.getInputStream();
     114        }
     115    }
     116
     117    @Override
     118    public CachedFile getCachedFile() throws IOException {
     119        return new CachedFile(url).setHttpAccept(XML_STYLE_MIME_TYPES);
    120120    }
    121121
  • trunk/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java

    r7092 r7248  
    2222import java.io.File;
    2323import java.io.IOException;
     24import java.io.InputStream;
    2425import java.io.InputStreamReader;
    2526import java.net.MalformedURLException;
     
    8990import org.openstreetmap.josm.gui.widgets.JFileChooserManager;
    9091import org.openstreetmap.josm.gui.widgets.JosmTextField;
    91 import org.openstreetmap.josm.io.MirroredInputStream;
     92import org.openstreetmap.josm.io.CachedFile;
    9293import org.openstreetmap.josm.io.OsmTransferException;
    9394import org.openstreetmap.josm.tools.GBC;
     
    10441045        @Override
    10451046        public void actionPerformed(ActionEvent e) {
    1046             MirroredInputStream.cleanup(url);
     1047            CachedFile.cleanup(url);
    10471048            reloadAvailableSources(url, sourceProviders);
    10481049        }
     
    12801281                }
    12811282
    1282                 MirroredInputStream stream = new MirroredInputStream(url);
     1283                InputStream stream = new CachedFile(url).getInputStream();
    12831284                reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
    12841285
  • trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetReader.java

    r7082 r7248  
    2525import org.openstreetmap.josm.Main;
    2626import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
    27 import org.openstreetmap.josm.io.MirroredInputStream;
     27import org.openstreetmap.josm.io.CachedFile;
    2828import org.openstreetmap.josm.tools.XmlObjectParser;
    2929import org.xml.sax.SAXException;
     
    225225    public static Collection<TaggingPreset> readAll(String source, boolean validate) throws SAXException, IOException {
    226226        Collection<TaggingPreset> tp;
     227        CachedFile cf = new CachedFile(source).setHttpAccept(PRESET_MIME_TYPES);
    227228        try (
    228             MirroredInputStream s = new MirroredInputStream(source, null, PRESET_MIME_TYPES);
    229229            // zip may be null, but Java 7 allows it: https://blogs.oracle.com/darcy/entry/project_coin_null_try_with
    230             InputStream zip = s.findZipEntryInputStream("xml", "preset")
     230            InputStream zip = cf.findZipEntryInputStream("xml", "preset")
    231231        ) {
    232232            if (zip != null) {
    233                 zipIcons = s.getFile();
    234             }
    235             try (InputStreamReader r = new InputStreamReader(zip == null ? s : zip, StandardCharsets.UTF_8)) {
     233                zipIcons = cf.getFile();
     234            }
     235            try (InputStreamReader r = new InputStreamReader(zip == null ? cf.getInputStream() : zip, StandardCharsets.UTF_8)) {
    236236                tp = readAll(new BufferedReader(r), validate);
    237237            }
  • trunk/src/org/openstreetmap/josm/io/CachedFile.java

    r7247 r7248  
    2828
    2929/**
    30  * Mirrors a file to a local file.
     30 * Downloads a file and caches it on disk in order to reduce network load.
     31 *
     32 * Supports URLs, local files, and a custom scheme (<code>resource:</code>) to get
     33 * resources from the current *.jar file. (Local caching is only done for URLs.)
    3134 * <p>
    32  * The file mirrored is only downloaded if it has been more than 7 days since last download
     35 * The mirrored file is only downloaded if it has been more than 7 days since
     36 * last download. (Time can be configured.)
     37 * <p>
     38 * The file content is normally accessed with {@link #getInputStream()}, but
     39 * you can also get the mirrored copy with {@link #getFile()}.
    3340 */
    34 public class MirroredInputStream extends InputStream {
    35    
     41public class CachedFile {
     42
    3643    /**
    3744     * Caching strategy.
     
    5158        IfModifiedSince
    5259    }
     60    protected String name;
     61    protected long maxAge;
     62    protected String destDir;
     63    protected String httpAccept;
     64    protected CachingStrategy cachingStrategy;
    5365   
    54     InputStream fs = null;
    55     File file = null;
     66    protected File cacheFile = null;
     67    boolean initialized = false;
    5668
    5769    public static final long DEFAULT_MAXTIME = -1L;
     
    5971
    6072    /**
    61      * Constructs an input stream from a given filename, URL or internal resource.
     73     * Constructs a CachedFile object from a given filename, URL or internal resource.
    6274     *
    6375     * @param name can be:<ul>
    6476     *  <li>relative or absolute file name</li>
    6577     *  <li>{@code file:///SOME/FILE} the same as above</li>
     78     *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    6679     *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    67      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    68      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    69      * @throws IOException when the resource with the given name could not be retrieved
    70      */
    71     public MirroredInputStream(String name) throws IOException {
    72         this(name, null, DEFAULT_MAXTIME, null);
    73     }
    74 
    75     /**
    76      * Constructs an input stream from a given filename, URL or internal resource.
    77      *
     80     *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li></ul>
     81     */
     82    public CachedFile(String name) {
     83        this.name = name;
     84    }
     85
     86    /**
     87     * Set the name of the resource.
    7888     * @param name can be:<ul>
    7989     *  <li>relative or absolute file name</li>
    8090     *  <li>{@code file:///SOME/FILE} the same as above</li>
     91     *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    8192     *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    82      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    83      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    84      * @param maxTime the maximum age of the cache file (in seconds)
     93     *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li></ul>
     94     * @return this object
     95     */
     96    public CachedFile setName(String name) {
     97        this.name = name;
     98        return this;
     99    }
     100   
     101    /**
     102     * Set maximum age of cache file. Only applies to URLs.
     103     * When this time has passed after the last download of the file, the
     104     * cache is considered stale and a new download will be attempted.
     105     * @param maxAge the maximum cache age in seconds
     106     * @return this object
     107     */
     108    public CachedFile setMaxAge(long maxAge) {
     109        this.maxAge = maxAge;
     110        return this;
     111    }
     112
     113    /**
     114     * Set the destination directory for the cache file. Only applies to URLs.
     115     * @param destDir the destination directory
     116     * @return this object
     117     */
     118    public CachedFile setDestDir(String destDir) {
     119        this.destDir = destDir;
     120        return this;
     121    }
     122
     123    /**
     124     * Set the accepted MIME types sent in the HTTP Accept header. Only applies to URLs.
     125     * @param httpAccept the accepted MIME types
     126     * @return this object
     127     */
     128    public CachedFile setHttpAccept(String httpAccept) {
     129        this.httpAccept = httpAccept;
     130        return this;
     131    }
     132
     133    /**
     134     * Set the caching strategy. Only applies to URLs.
     135     * @param cachingStrategy
     136     * @return this object
     137     */
     138    public CachedFile setCachingStrategy(CachingStrategy cachingStrategy) {
     139        this.cachingStrategy = cachingStrategy;
     140        return this;
     141    }
     142
     143    public String getName() {
     144        return name;
     145    }
     146
     147    public long getMaxAge() {
     148        return maxAge;
     149    }
     150
     151    public String getDestDir() {
     152        return destDir;
     153    }
     154
     155    public String getHttpAccept() {
     156        return httpAccept;
     157    }
     158
     159    public CachingStrategy getCachingStrategy() {
     160        return cachingStrategy;
     161    }
     162
     163    /**
     164     * Get InputStream to the requested resource.
     165     * @return the InputStream
    85166     * @throws IOException when the resource with the given name could not be retrieved
    86167     */
    87     public MirroredInputStream(String name, long maxTime) throws IOException {
    88         this(name, null, maxTime, null);
    89     }
    90 
    91     /**
    92      * Constructs an input stream from a given filename, URL or internal resource.
    93      *
    94      * @param name can be:<ul>
    95      *  <li>relative or absolute file name</li>
    96      *  <li>{@code file:///SOME/FILE} the same as above</li>
    97      *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    98      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    99      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    100      * @param destDir the destination directory for the cache file. Only applies for URLs.
     168    public InputStream getInputStream() throws IOException {
     169        File file = getFile();
     170        if (file == null) {
     171            if (name.startsWith("resource://")) {
     172                InputStream is = getClass().getResourceAsStream(
     173                        name.substring("resource:/".length()));
     174                if (is == null)
     175                    throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
     176                return is;
     177            }
     178        }
     179        return new FileInputStream(file);
     180    }
     181
     182    /**
     183     * Get local file for the requested resource.
     184     * @return The local cache file for URLs. If the resource is a local file,
     185     * returns just that file.
    101186     * @throws IOException when the resource with the given name could not be retrieved
    102187     */
    103     public MirroredInputStream(String name, String destDir) throws IOException {
    104         this(name, destDir, DEFAULT_MAXTIME, null);
    105     }
    106 
    107     /**
    108      * Constructs an input stream from a given filename, URL or internal resource.
    109      *
    110      * @param name can be:<ul>
    111      *  <li>relative or absolute file name</li>
    112      *  <li>{@code file:///SOME/FILE} the same as above</li>
    113      *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    114      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    115      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    116      * @param destDir the destination directory for the cache file. Only applies for URLs.
    117      * @param maxTime the maximum age of the cache file (in seconds)
    118      * @throws IOException when the resource with the given name could not be retrieved
    119      */
    120     public MirroredInputStream(String name, String destDir, long maxTime) throws IOException {
    121         this(name, destDir, maxTime, null);
    122     }
    123 
    124     /**
    125      * Constructs an input stream from a given filename, URL or internal resource.
    126      *
    127      * @param name can be:<ul>
    128      *  <li>relative or absolute file name</li>
    129      *  <li>{@code file:///SOME/FILE} the same as above</li>
    130      *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    131      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    132      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    133      * @param destDir the destination directory for the cache file. Only applies for URLs.
    134      * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Only applies for URLs.
    135      * @throws IOException when the resource with the given name could not be retrieved
    136      * @since 6867
    137      */
    138     public MirroredInputStream(String name, String destDir, String httpAccept) throws IOException {
    139         this(name, destDir, DEFAULT_MAXTIME, httpAccept);
    140     }
    141 
    142     /**
    143      * Constructs an input stream from a given filename, URL or internal resource.
    144      *
    145      * @param name can be:<ul>
    146      *  <li>relative or absolute file name</li>
    147      *  <li>{@code file:///SOME/FILE} the same as above</li>
    148      *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    149      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    150      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    151      * @param destDir the destination directory for the cache file. Only applies for URLs.
    152      * @param maxTime the maximum age of the cache file (in seconds)
    153      * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Only applies for URLs.
    154      * @throws IOException when the resource with the given name could not be retrieved
    155      * @since 6867
    156      */
    157     public MirroredInputStream(String name, String destDir, long maxTime, String httpAccept) throws IOException {
    158         this(name, destDir, maxTime, httpAccept, CachingStrategy.MaxAge);
    159     }
    160 
    161     /**
    162      * Constructs an input stream from a given filename, URL or internal resource.
    163      *
    164      * @param name can be:<ul>
    165      *  <li>relative or absolute file name</li>
    166      *  <li>{@code file:///SOME/FILE} the same as above</li>
    167      *  <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
    168      *  <li>{@code josmdir://SOME/FILE} file inside josm config directory (since r7058)</li>
    169      *  <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
    170      * @param destDir the destination directory for the cache file. Only applies for URLs.
    171      * @param maxTime the maximum age of the cache file (in seconds)
    172      * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Only applies for URLs.
    173      * @param caching the caching strategy
    174      * @throws IOException when the resource with the given name could not be retrieved
    175      * @since 6867
    176      */
    177     public MirroredInputStream(String name, String destDir, long maxTime, String httpAccept, CachingStrategy caching) throws IOException {
     188    public File getFile() throws IOException {
     189        if (initialized)
     190            return cacheFile;
     191        initialized = true;
    178192        URL url;
    179193        try {
    180194            url = new URL(name);
    181195            if ("file".equals(url.getProtocol())) {
    182                 file = new File(name.substring("file:/".length()));
    183                 if (!file.exists()) {
    184                     file = new File(name.substring("file://".length()));
     196                cacheFile = new File(name.substring("file:/".length()));
     197                if (!cacheFile.exists()) {
     198                    cacheFile = new File(name.substring("file://".length()));
    185199                }
    186200            } else {
    187                 file = checkLocal(url, destDir, maxTime, httpAccept, caching);
     201                cacheFile = checkLocal(url);
    188202            }
    189203        } catch (java.net.MalformedURLException e) {
    190204            if (name.startsWith("resource://")) {
    191                 fs = getClass().getResourceAsStream(
    192                         name.substring("resource:/".length()));
    193                 if (fs == null)
    194                     throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
    195                 return;
     205                return null;
    196206            } else if (name.startsWith("josmdir://")) {
    197                 file = new File(Main.pref.getPreferencesDir(), name.substring("josmdir://".length()));
     207                cacheFile = new File(Main.pref.getPreferencesDir(), name.substring("josmdir://".length()));
    198208            } else {
    199                 file = new File(name);
    200             }
    201         }
    202         if (file == null)
     209                cacheFile = new File(name);
     210            }
     211        }
     212        if (cacheFile == null)
    203213            throw new IOException();
    204         fs = new FileInputStream(file);
    205     }
    206 
     214        return cacheFile;
     215    }
     216   
    207217    /**
    208218     * Looks for a certain entry inside a zip file and returns the entry path.
     
    215225     * @param extension  the extension of the file we're looking for
    216226     * @param namepart the name part
    217      * @return The zip entry path of the matching file. Null if this mirrored
    218      * input stream doesn't represent a zip file or if there was no matching
     227     * @return The zip entry path of the matching file. Null if this cached file
     228     * doesn't represent a zip file or if there was no matching
    219229     * file in the ZIP file.
    220230     */
     
    227237    /**
    228238     * Like {@link #findZipEntryPath}, but returns the corresponding InputStream.
     239     * @param extension  the extension of the file we're looking for
     240     * @param namepart the name part
     241     * @return InputStream to the matching file. Null if this cached file
     242     * doesn't represent a zip file or if there was no matching
     243     * file in the ZIP file.
    229244     * @since 6148
    230245     */
     
    237252    @SuppressWarnings("resource")
    238253    private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
     254        File file = null;
     255        try {
     256            file = getFile();
     257        } catch (IOException ex) {
     258        }
    239259        if (file == null)
    240260            return null;
     
    270290
    271291    /**
    272      * Replies the local file.
    273      * @return The local file on disk
    274      */
    275     public File getFile() {
    276         return file;
    277     }
    278 
     292     * Clear the cache for the given resource.
     293     * This forces a fresh download.
     294     * @param name the URL
     295     */
    279296    public static void cleanup(String name) {
    280297        cleanup(name, null);
    281298    }
    282299
     300    /**
     301     * Clear the cache for the given resource.
     302     * This forces a fresh download.
     303     * @param name the URL
     304     * @param destDir the destination directory (see {@link #setDestDir(java.lang.String)})
     305     */
    283306    public static void cleanup(String name, String destDir) {
    284307        URL url;
     
    302325
    303326    /**
    304      * get preference key to store the location and age of the cached file.
     327     * Get preference key to store the location and age of the cached file.
    305328     * 2 resources that point to the same url, but that are to be stored in different
    306329     * directories will not share a cache file.
     
    316339    }
    317340
    318     private File checkLocal(URL url, String destDir, long maxTime, String httpAccept, CachingStrategy caching) throws IOException {
     341    private File checkLocal(URL url) throws IOException {
    319342        String prefKey = getPrefKey(url, destDir);
    320343        long age = 0L;
     344        long lMaxAge = maxAge;
    321345        Long ifModifiedSince = null;
    322346        File localFile = null;
     
    327351                localFile = null;
    328352            else {
    329                 if ( maxTime == DEFAULT_MAXTIME
    330                         || maxTime <= 0 // arbitrary value <= 0 is deprecated
     353                if ( maxAge == DEFAULT_MAXTIME
     354                        || maxAge <= 0 // arbitrary value <= 0 is deprecated
    331355                ) {
    332                     maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
     356                    lMaxAge = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
    333357                }
    334358                age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
    335                 if (age < maxTime*1000) {
     359                if (age < lMaxAge*1000) {
    336360                    return localFile;
    337361                }
    338                 if (caching == CachingStrategy.IfModifiedSince) {
     362                if (cachingStrategy == CachingStrategy.IfModifiedSince) {
    339363                    ifModifiedSince = Long.parseLong(localPathEntry.get(0));
    340364                }
     
    382406            }
    383407        } catch (IOException e) {
    384             if (age >= maxTime*1000 && age < maxTime*1000*2) {
     408            if (age >= lMaxAge*1000 && age < lMaxAge*1000*2) {
    385409                Main.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", url, e));
    386410                return localFile;
     
    463487    }
    464488
    465     @Override
    466     public int available() throws IOException
    467     { return fs.available(); }
    468     @Override
    469     public void close() throws IOException
    470     { Utils.close(fs); }
    471     @Override
    472     public int read() throws IOException
    473     { return fs.read(); }
    474     @Override
    475     public int read(byte[] b) throws IOException
    476     { return fs.read(b); }
    477     @Override
    478     public int read(byte[] b, int off, int len) throws IOException
    479     { return fs.read(b,off, len); }
    480     @Override
    481     public long skip(long n) throws IOException
    482     { return fs.skip(n); }
    483489}
  • trunk/src/org/openstreetmap/josm/io/FileWatcher.java

    r7244 r7248  
    5959            throw new IllegalStateException("File watcher is not available");
    6060        }
    61         try (MirroredInputStream mis = style.getMirroredInputStream()) {
    62             // Get underlying file
    63             File file = mis.getFile();
    64             if (file == null) {
    65                 throw new IllegalArgumentException("Style "+style+" does not have a local file");
    66             }
    67             // Get parent directory as WatchService allows only to monitor directories, not single files
    68             File dir = file.getParentFile();
    69             if (dir == null) {
    70                 throw new IllegalArgumentException("Style "+style+" does not have a parent directory");
    71             }
    72             synchronized(this) {
    73                 // Register directory. Can be called several times for a same directory without problem
    74                 // (it returns the same key so it should not send events several times)
    75                 dir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
    76                 styleMap.put(file.toPath(), style);
    77             }
     61        CachedFile cf = style.getCachedFile();
     62        // Get underlying file
     63        File file = cf.getFile();
     64        if (file == null) {
     65            throw new IllegalArgumentException("Style "+style+" does not have a local file");
     66        }
     67        // Get parent directory as WatchService allows only to monitor directories, not single files
     68        File dir = file.getParentFile();
     69        if (dir == null) {
     70            throw new IllegalArgumentException("Style "+style+" does not have a parent directory");
     71        }
     72        synchronized(this) {
     73            // Register directory. Can be called several times for a same directory without problem
     74            // (it returns the same key so it should not send events several times)
     75            dir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE);
     76            styleMap.put(file.toPath(), style);
    7877        }
    7978    }
  • trunk/src/org/openstreetmap/josm/io/imagery/ImageryReader.java

    r7242 r7248  
    1818import org.openstreetmap.josm.data.imagery.ImageryInfo.ImageryType;
    1919import org.openstreetmap.josm.data.imagery.Shape;
    20 import org.openstreetmap.josm.io.MirroredInputStream;
     20import org.openstreetmap.josm.io.CachedFile;
    2121import org.openstreetmap.josm.io.UTFInputStreamReader;
    2222import org.xml.sax.Attributes;
     
    5050            SAXParserFactory factory = SAXParserFactory.newInstance();
    5151            factory.setNamespaceAware(true);
    52             try (InputStream in = new MirroredInputStream(source, null, 1*MirroredInputStream.DAYS, null,
    53                     MirroredInputStream.CachingStrategy.IfModifiedSince)) {
     52            try (InputStream in = new CachedFile(source)
     53                    .setMaxAge(1*CachedFile.DAYS)
     54                    .setCachingStrategy(CachedFile.CachingStrategy.IfModifiedSince)
     55                    .getInputStream()) {
    5456                InputSource is = new InputSource(UTFInputStreamReader.create(in));
    5557                factory.newSAXParser().parse(is, parser);
  • trunk/src/org/openstreetmap/josm/plugins/PluginDownloadTask.java

    r7242 r7248  
    2222import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
    2323import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    24 import org.openstreetmap.josm.io.MirroredInputStream;
     24import org.openstreetmap.josm.io.CachedFile;
    2525import org.openstreetmap.josm.tools.CheckParameterUtil;
    2626import org.xml.sax.SAXException;
     
    125125            URL url = new URL(pi.downloadlink);
    126126            synchronized(this) {
    127                 downloadConnection = MirroredInputStream.connectFollowingRedirect(url, PLUGIN_MIME_TYPES, null);
     127                downloadConnection = CachedFile.connectFollowingRedirect(url, PLUGIN_MIME_TYPES, null);
    128128            }
    129129            try (
  • trunk/src/org/openstreetmap/josm/tools/ImageProvider.java

    r7134 r7248  
    5959import org.openstreetmap.josm.Main;
    6060import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
    61 import org.openstreetmap.josm.io.MirroredInputStream;
    6261import org.openstreetmap.josm.plugins.PluginHandler;
    6362import org.w3c.dom.Element;
     
    7574import com.kitfox.svg.SVGException;
    7675import com.kitfox.svg.SVGUniverse;
     76import org.openstreetmap.josm.io.CachedFile;
    7777
    7878/**
     
    533533
    534534    private static ImageResource getIfAvailableHttp(String url, ImageType type) {
    535         try (MirroredInputStream is = new MirroredInputStream(url,
    536                     new File(Main.pref.getCacheDirectory(), "images").getPath())) {
     535        CachedFile cf = new CachedFile(url)
     536                .setDestDir(new File(Main.pref.getCacheDirectory(), "images").getPath());
     537        try (InputStream is = cf.getInputStream()) {
    537538            switch (type) {
    538539            case SVG:
    539                 URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(is.getFile()).toString());
     540                URI uri = getSvgUniverse().loadSVG(is, Utils.fileToURL(cf.getFile()).toString());
    540541                SVGDiagram svg = getSvgUniverse().getDiagram(uri);
    541542                return svg == null ? null : new ImageResource(svg);
     
    543544                BufferedImage img = null;
    544545                try {
    545                     img = read(Utils.fileToURL(is.getFile()), false, false);
     546                    img = read(Utils.fileToURL(cf.getFile()), false, false);
    546547                } catch (IOException e) {
    547548                    Main.warn("IOException while reading HTTP image: "+e.getMessage());
     
    800801            });
    801802
    802             try (InputStream is = new MirroredInputStream(
    803                     base + fn,
    804                     new File(Main.pref.getPreferencesDir(), "images").toString())
    805             ) {
     803            CachedFile cf = new CachedFile(base + fn).setDestDir(new File(Main.pref.getPreferencesDir(), "images").toString());
     804            try (InputStream is = cf.getInputStream()) {
    806805                parser.parse(new InputSource(is));
    807806            }
  • trunk/src/org/openstreetmap/josm/tools/RightAndLefthandTraffic.java

    r7193 r7248  
    1111import org.openstreetmap.josm.data.osm.DataSet;
    1212import org.openstreetmap.josm.data.osm.Way;
     13import org.openstreetmap.josm.io.CachedFile;
    1314import org.openstreetmap.josm.io.IllegalDataException;
    14 import org.openstreetmap.josm.io.MirroredInputStream;
    1515import org.openstreetmap.josm.io.OsmReader;
    1616import org.openstreetmap.josm.tools.GeoPropertyIndex.GeoProperty;
     
    6767    private static void initialize() {
    6868        leftHandTrafficPolygons = new ArrayList<>();
    69         try (InputStream is = new MirroredInputStream("resource://data/left-right-hand-traffic.osm")) {
     69        try (InputStream is = new CachedFile("resource://data/left-right-hand-traffic.osm").getInputStream()) {
    7070            DataSet data = OsmReader.parseDataSet(is, null);
    7171            for (Way w : data.getWays()) {
  • trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java

    r7033 r7248  
    2828
    2929import org.openstreetmap.josm.Main;
    30 import org.openstreetmap.josm.io.MirroredInputStream;
     30import org.openstreetmap.josm.io.CachedFile;
    3131import org.xml.sax.Attributes;
    3232import org.xml.sax.ContentHandler;
     
    281281    public Iterable<Object> startWithValidation(final Reader in, String namespace, String schemaSource) throws SAXException {
    282282        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    283         try (InputStream mis = new MirroredInputStream(schemaSource)) {
     283        try (InputStream mis = new CachedFile(schemaSource).getInputStream()) {
    284284            Schema schema = factory.newSchema(new StreamSource(mis));
    285285            ValidatorHandler validator = schema.newValidatorHandler();
Note: See TracChangeset for help on using the changeset viewer.