Changeset 10235 in josm


Ignore:
Timestamp:
2016-05-17T02:02:30+02:00 (4 years ago)
Author:
Don-vip
Message:

sonar - squid:S00112 - Generic exceptions should never be thrown

Location:
trunk
Files:
1 added
20 edited

Legend:

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

    r10169 r10235  
    158158
    159159    @SuppressWarnings("unchecked")
    160     private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath) {
     160    private static <K, V> CacheAccess<K, V> getCacheInner(String cacheName, int maxMemoryObjects, int maxDiskObjects, String cachePath)
     161            throws IOException {
    161162        CompositeCache<K, V> cc = cacheManager.getCache(cacheName, getCacheAttributes(maxMemoryObjects));
    162163
     
    169170                    cc.setAuxCaches(new AuxiliaryCache[]{diskCache});
    170171                }
     172            } catch (IOException e) {
     173                throw e;
    171174            } catch (Exception e) {
    172                 throw new RuntimeException(e);
     175                throw new IOException(e);
    173176            }
    174177        }
  • trunk/src/org/openstreetmap/josm/data/imagery/CachedTileLoaderFactory.java

    r9067 r10235  
    44import java.io.File;
    55import java.lang.reflect.Constructor;
    6 import java.lang.reflect.InvocationTargetException;
    76import java.util.Map;
    87import java.util.concurrent.ConcurrentHashMap;
     
    3332     * @param cache cache instance which will be used by tile loaders created by this tile loader
    3433     * @param tileLoaderClass tile loader class that will be created
    35      *
     34     * @throws IllegalArgumentException if a suitable constructor cannot be found for {@code tileLoaderClass}
    3635     */
    3736    public CachedTileLoaderFactory(ICacheAccess<String, BufferedImageCacheEntry> cache, Class<? extends TileLoader> tileLoaderClass) {
     
    4645        } catch (NoSuchMethodException | SecurityException e) {
    4746            Main.warn(e);
    48             throw new RuntimeException(e);
     47            throw new IllegalArgumentException(e);
    4948        }
    5049    }
     
    8887                    readTimeout,
    8988                    headers);
    90         } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
     89        } catch (IllegalArgumentException e) {
    9190            Main.warn(e);
    92             throw new RuntimeException(e);
     91            throw e;
     92        } catch (ReflectiveOperationException e) {
     93            Main.warn(e);
     94            throw new IllegalArgumentException(e);
    9395        }
    9496    }
  • trunk/src/org/openstreetmap/josm/data/preferences/ListListSetting.java

    r9759 r10235  
    7474        if (value != null) {
    7575            if (value.contains(null))
    76                 throw new RuntimeException("Error: Null as list element in preference setting");
     76                throw new IllegalArgumentException("Error: Null as list element in preference setting");
    7777            for (Collection<String> lst : value) {
    7878                if (lst.contains(null)) {
    79                     throw new RuntimeException("Error: Null as inner list element in preference setting");
     79                    throw new IllegalArgumentException("Error: Null as inner list element in preference setting");
    8080                }
    8181            }
  • trunk/src/org/openstreetmap/josm/data/preferences/ListSetting.java

    r9759 r10235  
    4444    private void consistencyTest() {
    4545        if (value != null && value.contains(null))
    46             throw new RuntimeException("Error: Null as list element in preference setting");
     46            throw new IllegalArgumentException("Error: Null as list element in preference setting");
    4747    }
    4848
  • trunk/src/org/openstreetmap/josm/data/preferences/MapListSetting.java

    r9759 r10235  
    7373            return;
    7474        if (value.contains(null))
    75             throw new RuntimeException("Error: Null as list element in preference setting");
     75            throw new IllegalArgumentException("Error: Null as list element in preference setting");
    7676        for (Map<String, String> map : value) {
    7777            if (map.keySet().contains(null))
    78                 throw new RuntimeException("Error: Null as map key in preference setting");
     78                throw new IllegalArgumentException("Error: Null as map key in preference setting");
    7979            if (map.values().contains(null))
    80                 throw new RuntimeException("Error: Null as map value in preference setting");
     80                throw new IllegalArgumentException("Error: Null as map value in preference setting");
    8181        }
    8282    }
  • trunk/src/org/openstreetmap/josm/data/preferences/PreferencesReader.java

    r9978 r10235  
    3131import org.openstreetmap.josm.Main;
    3232import org.openstreetmap.josm.io.CachedFile;
     33import org.openstreetmap.josm.io.XmlStreamParsingException;
    3334import org.xml.sax.SAXException;
    3435
     
    3738 */
    3839public class PreferencesReader {
    39 
    40     private static final String XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
    4140
    4241    private final SortedMap<String, Setting<?>> settings = new TreeMap<>();
     
    118117    }
    119118
     119    /**
     120     * Parse preferences.
     121     * @throws XMLStreamException if any XML parsing error occurs
     122     * @throws IOException if any I/O error occurs
     123     */
    120124    public void parse() throws XMLStreamException, IOException {
    121125        if (reader != null) {
     
    168172                switch(localName) {
    169173                case "tag":
    170                     Setting setting;
     174                    StringSetting setting;
    171175                    if (defaults && isNil()) {
    172176                        setting = new StringSetting(null);
     
    221225        List<Map<String, String>> maps = null;
    222226        if (defaults && isNil()) {
    223             Setting setting;
     227            Setting<?> setting;
    224228            switch (name) {
    225229                case "lists":
     
    268272                }
    269273            }
    270             Setting setting;
     274            Setting<?> setting;
    271275            if (entries != null) {
    272276                setting = new ListSetting(Collections.unmodifiableList(entries));
     
    337341     */
    338342    private boolean isNil() {
    339         String nil = parser.getAttributeValue(XSI_NS, "nil");
     343        String nil = parser.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "nil");
    340344        return "true".equals(nil) || "1".equals(nil);
    341345    }
    342346
    343347    /**
    344      * Throw RuntimeException with line and column number.
     348     * Throw XmlStreamParsingException with line and column number.
    345349     *
    346350     * Only use this for errors that should not be possible after schema validation.
    347351     * @param msg the error message
    348      */
    349     private void throwException(String msg) {
    350         throw new RuntimeException(msg + tr(" (at line {0}, column {1})",
    351                 parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber()));
     352     * @throws XmlStreamParsingException always
     353     */
     354    private void throwException(String msg) throws XmlStreamParsingException {
     355        throw new XmlStreamParsingException(msg, parser.getLocation());
    352356    }
    353357}
  • trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java

    r10212 r10235  
    775775            ret.put("oslo", parseAngle("10d43'22.5\"E", null));
    776776        } catch (ProjectionConfigurationException ex) {
    777             throw new RuntimeException();
     777            throw new IllegalStateException(ex);
    778778        }
    779779        return ret;
  • trunk/src/org/openstreetmap/josm/data/projection/proj/AbstractProj.java

    r9992 r10235  
    138138        for (i = MAXIMUM_ITERATIONS; true;) { // rarely goes over 5 iterations
    139139            if (--i < 0) {
    140                 throw new RuntimeException("Too many iterations");
     140                throw new IllegalStateException("Too many iterations");
    141141            }
    142142            s = Math.sin(phi);
     
    162162            }
    163163        }
    164         throw new RuntimeException("no convergence");
     164        throw new IllegalStateException("no convergence for ts="+ts);
    165165    }
    166166
  • trunk/src/org/openstreetmap/josm/data/projection/proj/AlbersEqualArea.java

    r10001 r10235  
    126126                rho = 0.0;
    127127            } else {
    128                 throw new RuntimeException();
     128                throw new AssertionError();
    129129            }
    130130        }
     
    184184            }
    185185        }
    186         throw new RuntimeException("no convergence for q="+qs);
     186        throw new IllegalStateException("no convergence for qs="+qs);
    187187    }
    188188
  • trunk/src/org/openstreetmap/josm/data/projection/proj/DoubleStereographic.java

    r10001 r10235  
    100100        while (abs(phi - phiprev) > EPSILON) {
    101101            if (++iteration > 10)
    102                 throw new RuntimeException("Too many iterations");
     102                throw new IllegalStateException("Too many iterations");
    103103            phiprev = phi;
    104104            double psii = log(tan(phi/2 + PI/4) * pow((1 - e * sin(phi)) / (1 + e * sin(phi)), e/2));
  • trunk/src/org/openstreetmap/josm/data/projection/proj/PolarStereographic.java

    r10001 r10235  
    163163            phi0 = phi;
    164164            if (--i < 0) {
    165                 throw new RuntimeException("no convergence");
     165                throw new IllegalStateException("no convergence for x="+x+", y="+y);
    166166            }
    167167        }
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r10217 r10235  
    2222import java.security.AllPermission;
    2323import java.security.CodeSource;
     24import java.security.GeneralSecurityException;
    2425import java.security.KeyStoreException;
    2526import java.security.NoSuchAlgorithmException;
     
    413414        try {
    414415            CertificateAmendment.addMissingCertificates();
    415         } catch (IOException ex) {
     416        } catch (IOException | GeneralSecurityException ex) {
    416417            ex.printStackTrace();
    417418            Main.warn(getErrorMessage(Utils.getRootCause(ex)));
  • trunk/src/org/openstreetmap/josm/gui/preferences/SourceEditor.java

    r10212 r10235  
    498498     * Synchronously loads available sources and returns the parsed list.
    499499     * @return list of available sources
     500     * @throws OsmTransferException in case of OSM transfer error
     501     * @throws IOException in case of any I/O error
     502     * @throws SAXException in case of any SAX error
    500503     */
    501     public final Collection<ExtendedSourceEntry> loadAndGetAvailableSources() {
    502         try {
    503             final SourceLoader loader = new SourceLoader(availableSourcesUrl, sourceProviders);
    504             loader.realRun();
    505             return loader.sources;
    506         } catch (IOException | SAXException | OsmTransferException ex) {
    507             throw new RuntimeException(ex);
    508         }
     504    public final Collection<ExtendedSourceEntry> loadAndGetAvailableSources() throws SAXException, IOException, OsmTransferException {
     505        final SourceLoader loader = new SourceLoader(availableSourcesUrl, sourceProviders);
     506        loader.realRun();
     507        return loader.sources;
    509508    }
    510509
  • trunk/src/org/openstreetmap/josm/io/CertificateAmendment.java

    r10088 r10235  
    1111import java.nio.file.Path;
    1212import java.nio.file.Paths;
     13import java.security.GeneralSecurityException;
    1314import java.security.InvalidAlgorithmParameterException;
    14 import java.security.KeyManagementException;
    1515import java.security.KeyStore;
    1616import java.security.KeyStoreException;
    1717import java.security.MessageDigest;
    18 import java.security.NoSuchAlgorithmException;
    19 import java.security.cert.CertificateException;
    2018import java.security.cert.CertificateFactory;
    2119import java.security.cert.PKIXParameters;
     
    5957     * Add missing root certificates to the list of trusted certificates for TLS connections.
    6058     * @throws IOException if an I/O error occurs
     59     * @throws GeneralSecurityException if a security error occurs
    6160     */
    62     public static void addMissingCertificates() throws IOException {
     61    public static void addMissingCertificates() throws IOException, GeneralSecurityException {
    6362        if (!Main.pref.getBoolean("tls.add-missing-certificates", true))
    6463            return;
    65         KeyStore keyStore;
    66         try {
    67             keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    68         } catch (KeyStoreException ex) {
    69             throw new IOException(ex);
    70         }
     64        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    7165        Path cacertsPath = Paths.get(System.getProperty("java.home"), "lib", "security", "cacerts");
    7266        try (InputStream is = Files.newInputStream(cacertsPath)) {
    7367            keyStore.load(is, "changeit".toCharArray());
    74         } catch (NoSuchAlgorithmException ex) {
    75             throw new RuntimeException(ex);
    76         } catch (CertificateException ex) {
    77             throw new IOException(ex);
    7868        }
    7969
    80         CertificateFactory cf;
    81         try {
    82             cf = CertificateFactory.getInstance("X.509");
    83         } catch (CertificateException ex) {
    84             throw new RuntimeException(ex);
    85         }
     70        CertificateFactory cf = CertificateFactory.getInstance("X.509");
    8671        boolean certificateAdded = false;
    8772        for (int i = 0; i < CERT_AMEND.length; i++) {
    88             CachedFile certCF = new CachedFile(CERT_AMEND[i]);
    89             byte[] certBytes = certCF.getByteContent();
    90             ByteArrayInputStream certIS = new ByteArrayInputStream(certBytes);
    91             X509Certificate cert;
    92 
    93             try {
    94                 cert = (X509Certificate) cf.generateCertificate(certIS);
     73            try (CachedFile certCF = new CachedFile(CERT_AMEND[i])) {
     74                byte[] certBytes = certCF.getByteContent();
     75                ByteArrayInputStream certIS = new ByteArrayInputStream(certBytes);
     76                X509Certificate cert = (X509Certificate) cf.generateCertificate(certIS);
    9577                MessageDigest md = MessageDigest.getInstance("SHA-256");
    9678                String sha1 = Utils.toHexString(md.digest(cert.getEncoded()));
    9779                if (!SHA_HASHES[i].equals(sha1)) {
    98                     throw new RuntimeException(tr("Error adding certificate {0} - certificate fingerprint mismatch. Expected {1}, was {2}",
     80                    throw new IllegalStateException(
     81                            tr("Error adding certificate {0} - certificate fingerprint mismatch. Expected {1}, was {2}",
    9982                            CERT_AMEND[i],
    10083                            SHA_HASHES[i],
     
    10285                            ));
    10386                }
    104             } catch (CertificateException ex) {
    105                 throw new IOException(ex);
    106             } catch (NoSuchAlgorithmException ex) {
    107                 throw new RuntimeException(ex);
    108             }
    109             if (certificateIsMissing(keyStore, cert)) {
    110                 if (Main.isDebugEnabled()) {
    111                     Main.debug(tr("Adding certificate for TLS connections: {0}", cert.getSubjectX500Principal().getName()));
     87                if (certificateIsMissing(keyStore, cert)) {
     88                    if (Main.isDebugEnabled()) {
     89                        Main.debug(tr("Adding certificate for TLS connections: {0}", cert.getSubjectX500Principal().getName()));
     90                    }
     91                    String alias = "josm:" + new File(CERT_AMEND[i]).getName();
     92                    keyStore.setCertificateEntry(alias, cert);
     93                    certificateAdded = true;
    11294                }
    113                 String alias = "josm:" + new File(CERT_AMEND[i]).getName();
    114                 try {
    115                     keyStore.setCertificateEntry(alias, cert);
    116                 } catch (KeyStoreException ex) {
    117                     throw new AssertionError(ex);
    118                 }
    119                 certificateAdded = true;
    12095            }
    12196        }
    12297
    12398        if (certificateAdded) {
    124             try {
    125                 TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    126                 tmf.init(keyStore);
    127                 SSLContext sslContext = SSLContext.getInstance("TLS");
    128                 sslContext.init(null, tmf.getTrustManagers(), null);
    129                 SSLContext.setDefault(sslContext);
    130             } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
    131                 throw new RuntimeException(ex);
    132             }
     99            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
     100            tmf.init(keyStore);
     101            SSLContext sslContext = SSLContext.getInstance("TLS");
     102            sslContext.init(null, tmf.getTrustManagers(), null);
     103            SSLContext.setDefault(sslContext);
    133104        }
    134105    }
     
    139110     * @param crt the certificate
    140111     * @return true, if the certificate is not contained in the keystore
     112     * @throws InvalidAlgorithmParameterException if the keystore does not contain at least one trusted certificate entry
     113     * @throws KeyStoreException if the keystore has not been initialized
    141114     */
    142     private static boolean certificateIsMissing(KeyStore keyStore, X509Certificate crt) {
    143         PKIXParameters params;
    144         try {
    145             params = new PKIXParameters(keyStore);
    146         } catch (KeyStoreException ex) {
    147             throw new AssertionError(ex);
    148         } catch (InvalidAlgorithmParameterException ex) {
    149             throw new RuntimeException(ex);
    150         }
     115    private static boolean certificateIsMissing(KeyStore keyStore, X509Certificate crt)
     116            throws KeyStoreException, InvalidAlgorithmParameterException {
     117        PKIXParameters params = new PKIXParameters(keyStore);
    151118        String id = crt.getSubjectX500Principal().getName();
    152119        for (TrustAnchor ta : params.getTrustAnchors()) {
  • trunk/src/org/openstreetmap/josm/io/OsmReader.java

    r10223 r10235  
    9595
    9696    protected void throwException(String msg, Throwable th) throws XMLStreamException {
    97         throw new OsmParsingException(msg, parser.getLocation(), th);
     97        throw new XmlStreamParsingException(msg, parser.getLocation(), th);
    9898    }
    9999
    100100    protected void throwException(String msg) throws XMLStreamException {
    101         throw new OsmParsingException(msg, parser.getLocation());
     101        throw new XmlStreamParsingException(msg, parser.getLocation());
    102102    }
    103103
     
    560560    }
    561561
    562     private static class OsmParsingException extends XMLStreamException {
    563 
    564         OsmParsingException(String msg, Location location) {
    565             super(msg); /* cannot use super(msg, location) because it messes with the message preventing localization */
    566             this.location = location;
    567         }
    568 
    569         OsmParsingException(String msg, Location location, Throwable th) {
    570             super(msg, th);
    571             this.location = location;
    572         }
    573 
    574         @Override
    575         public String getMessage() {
    576             String msg = super.getMessage();
    577             if (msg == null) {
    578                 msg = getClass().getName();
    579             }
    580             if (getLocation() == null)
    581                 return msg;
    582             msg += ' ' + tr("(at line {0}, column {1})", getLocation().getLineNumber(), getLocation().getColumnNumber());
    583             int offset = getLocation().getCharacterOffset();
    584             if (offset > -1) {
    585                 msg += ". "+ tr("{0} bytes have been read", offset);
    586             }
    587             return msg;
    588         }
    589     }
    590 
    591562    /**
    592563     * Exception thrown after user cancelation.
    593564     */
    594     private static final class OsmParsingCanceledException extends OsmParsingException implements ImportCancelException {
     565    private static final class OsmParsingCanceledException extends XmlStreamParsingException implements ImportCancelException {
    595566        /**
    596567         * Constructs a new {@code OsmParsingCanceledException}.
     
    639610        } catch (IllegalDataException e) {
    640611            throw e;
    641         } catch (OsmParsingException e) {
     612        } catch (XmlStreamParsingException e) {
    642613            throw new IllegalDataException(e.getMessage(), e);
    643614        } catch (XMLStreamException e) {
  • trunk/src/org/openstreetmap/josm/tools/OverpassTurboQueryWizard.java

    r10101 r10235  
    5252                    "}");
    5353        } catch (ScriptException | IOException ex) {
    54             throw new RuntimeException("Failed to initialize OverpassTurboQueryWizard", ex);
     54            throw new IllegalStateException("Failed to initialize OverpassTurboQueryWizard", ex);
    5555        }
    5656    }
  • trunk/test/unit/org/openstreetmap/josm/JOSMFixture.java

    r10222 r10235  
    77import java.io.IOException;
    88import java.nio.file.Paths;
     9import java.security.GeneralSecurityException;
    910import java.text.MessageFormat;
    1011import java.util.Locale;
     
    9899        try {
    99100            CertificateAmendment.addMissingCertificates();
    100         } catch (IOException ex) {
     101        } catch (IOException | GeneralSecurityException ex) {
    101102            throw new RuntimeException(ex);
    102103        }
  • trunk/test/unit/org/openstreetmap/josm/gui/preferences/map/MapPaintPreferenceTestIT.java

    r10222 r10235  
    55import static org.junit.Assert.assertTrue;
    66
    7 import java.io.IOException;
    87import java.util.Collection;
    98import java.util.Collections;
     
    2423import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
    2524import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
    26 import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
    2725import org.openstreetmap.josm.gui.preferences.SourceEditor.ExtendedSourceEntry;
    2826
     
    5149    /**
    5250     * Test that available map paint styles are valid.
    53      * @throws IOException if any I/O error occurs
    54      * @throws ParseException if the config file does not match MapCSS syntax
     51     * @throws Exception in case of error
    5552     */
    5653    @Test
    57     public void testValidityOfAvailableStyles() throws ParseException, IOException {
     54    public void testValidityOfAvailableStyles() throws Exception {
    5855        Collection<ExtendedSourceEntry> sources = new MapPaintPreference.MapPaintSourceEditor()
    5956                .loadAndGetAvailableSources();
  • trunk/test/unit/org/openstreetmap/josm/gui/preferences/map/TaggingPresetPreferenceTestIT.java

    r10222 r10235  
    4646    /**
    4747     * Test that available tagging presets are valid.
     48     * @throws Exception in case of error
    4849     */
    4950    @Test
    50     public void testValidityOfAvailablePresets() {
     51    public void testValidityOfAvailablePresets() throws Exception {
    5152        Collection<ExtendedSourceEntry> sources = new TaggingPresetPreference.TaggingPresetSourceEditor()
    5253                .loadAndGetAvailableSources();
  • trunk/test/unit/org/openstreetmap/josm/gui/preferences/validator/ValidatorTagCheckerRulesPreferenceTestIT.java

    r9669 r10235  
    1414import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker;
    1515import org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.ParseResult;
    16 import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
    1716import org.openstreetmap.josm.gui.preferences.SourceEditor.ExtendedSourceEntry;
    1817
     
    3231    /**
    3332     * Test that available tag checker rules are valid.
    34      * @throws IOException if any I/O error occurs
    35      * @throws ParseException if the config file does not match MapCSS syntax
     33     * @throws Exception in case of error
    3634     */
    3735    @Test
    38     public void testValidityOfAvailableRules() throws ParseException, IOException {
     36    public void testValidityOfAvailableRules() throws Exception {
    3937        Collection<ExtendedSourceEntry> sources = new ValidatorTagCheckerRulesPreference.TagCheckerRulesSourceEditor()
    4038                .loadAndGetAvailableSources();
Note: See TracChangeset for help on using the changeset viewer.