Ignore:
Timestamp:
2022-08-04T15:43:42+02:00 (2 years ago)
Author:
taylor.smock
Message:

Fix #22263: Could not load plug-in 'ImportImagePlugin' due to log4j errors

This moves the plugin logging from log4j to the JOSM Logging class.

It also cleans up various lint issues and moves the unit tests from JUnit 4 to JUnit 5.

Location:
applications/editors/josm/plugins/ImportImagePlugin
Files:
1 deleted
10 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/ImportImagePlugin/.classpath

    r34444 r36013  
    1111        <classpathentry combineaccessrules="false" kind="src" path="/JOSM-GeoTools"/>
    1212        <classpathentry combineaccessrules="false" kind="src" path="/JOSM-jts"/>
    13         <classpathentry combineaccessrules="false" kind="src" path="/JOSM-log4j"/>
    14         <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
     13        <classpathentry combineaccessrules="false" kind="src" path="/JOSM-ejml"/>
     14        <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5"/>
    1515        <classpathentry kind="output" path="bin"/>
    1616</classpath>
  • applications/editors/josm/plugins/ImportImagePlugin/build.xml

    r34519 r36013  
    1212    <property name="plugin.icon" value="images/layericon.png"/>
    1313    <property name="plugin.link" value="https://wiki.openstreetmap.org/wiki/JOSM/Plugins/ImportImagePlugin"/>
    14     <property name="plugin.requires" value="log4j;jts;ejml;geotools"/>
     14    <property name="plugin.requires" value="jts;ejml;geotools"/>
    1515   
    1616    <!-- ** include targets that all plugins have in common ** -->
     
    1818
    1919    <fileset id="plugin.requires.jars" dir="${plugin.dist.dir}">
    20         <include name="log4j.jar"/>
    2120        <include name="jts.jar"/>
    2221        <include name="ejml.jar"/>
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageLayer.java

    r34519 r36013  
    1919import javax.swing.ImageIcon;
    2020
    21 import org.apache.log4j.Logger;
    2221import org.geotools.coverage.grid.GridCoverage2D;
    2322import org.geotools.geometry.Envelope2D;
     
    2524import org.geotools.referencing.CRS;
    2625import org.opengis.referencing.FactoryException;
    27 import org.opengis.referencing.NoSuchAuthorityCodeException;
    2826import org.opengis.referencing.crs.CoordinateReferenceSystem;
    2927import org.openstreetmap.josm.actions.RenameLayerAction;
     
    4947public class ImageLayer extends Layer {
    5048
    51     private Logger logger = Logger.getLogger(ImageLayer.class);
    52 
    53     private File imageFile;
    54 
    55     private BufferedImage image = null;
     49    private final File imageFile;
     50
     51    private BufferedImage image;
    5652
    5753    // coordinates of upper left corner
    5854    private EastNorth upperLeft;
    5955    // Angle of rotation of the image
    60     private double angle = 0.0;
     56    private double angle;
    6157
    6258    // current bbox
     
    6460
    6561    // Layer icon
    66     private Icon layericon = null;
    67 
    68     // reference system of the oringinal image
     62    private Icon layericon;
     63
     64    // reference system of the original image
    6965    private CoordinateReferenceSystem sourceRefSys;
    7066
     
    8985
    9086        // geotools type for images and value coverages
    91         GridCoverage2D coverage = null;
     87        GridCoverage2D coverage;
    9288        try {
    9389            // create a grid coverage from the image
     
    9995
    10096        } catch (FactoryException e) {
    101             logger.error("Error while creating GridCoverage:", e);
     97            Logging.error("ImportImagePlugin ImageLayer: Error while creating GridCoverage: {0}", e);
     98            Logging.error(e);
    10299            throw new IOException(e.getMessage());
    103100        } catch (Exception e) {
     
    105102                int val = 2;
    106103                if (!GraphicsEnvironment.isHeadless()) {
    107                     ExtendedDialog ex = new ExtendedDialog(MainApplication.getMainFrame(), tr("Warning"), 
    108                         new String[] {tr("Default image projection"), tr("JOSM''s current projection"), tr("Cancel")});
     104                    ExtendedDialog ex = new ExtendedDialog(MainApplication.getMainFrame(), tr("Warning"),
     105                            tr("Default image projection"), tr("JOSM''s current projection"), tr("Cancel"));
    109106                    // CHECKSTYLE.OFF: LineLength
    110107                    ex.setContent(tr("No projection file (.prj) found.<br>"
     
    115112                    val = ex.showDialog().getValue();
    116113                    if (val == 3) {
    117                         logger.debug("No projection and user declined un-projected use");
     114                        Logging.debug("ImportImagePlugin ImageLayer: No projection and user declined un-projected use");
    118115                        throw new LayerCreationCanceledException();
    119116                    }
    120117                }
    121                 CoordinateReferenceSystem src = null;
     118                CoordinateReferenceSystem src;
    122119                try {
    123120                    if (val == 1) {
    124121                        src = PluginOperations.defaultSourceCRS;
    125122                    } else {
    126                         logger.debug("Passing through image un-projected.");
     123                        Logging.debug("ImportImagePlugin ImageLayer: Passing through image un-projected.");
    127124                        src = CRS.decode(ProjectionRegistry.getProjection().toCode());
    128125                    }
     
    134131                    }
    135132                } catch (Exception e1) {
    136                     logger.error("Error while creating GridCoverage:", e1);
     133                    Logging.error("ImportImagePlugin ImageLayer: Error while creating GridCoverage:");
     134                    Logging.error(e1);
    137135                    throw new IOException(e1);
    138136                }
    139137            } else {
    140                 logger.error("Error while creating GridCoverage:", e);
     138                Logging.error("ImportImagePlugin ImageLayer: Error while creating GridCoverage:");
     139                Logging.error(e);
    141140                throw new IOException(e);
    142141            }
    143142
    144143        }
    145         logger.debug("Coverage created: " + coverage);
     144        Logging.debug("ImportImagePlugin ImageLayer: Coverage created: {0}", coverage);
    146145
    147146        upperLeft = new EastNorth(coverage.getEnvelope2D().x,
     
    213212
    214213            if ((scalex > 10) || (scaley > 10)) {
    215                 logger.warn("Not drawing image - scale too big");
     214                Logging.warn("ImportImagePlugin ImageLayer: Not drawing image - scale too big");
    216215                return;
    217216            }
     
    227226
    228227        } else {
    229             logger.error("Error while dawing image: image == null or Graphics == null");
     228            Logging.error("ImportImagePlugin ImageLayer: Error while drawing image: image == null or Graphics == null");
    230229        }
    231230    }
     
    295294     * calculated by the new reference system.
    296295     */
    297     void resample(CoordinateReferenceSystem refSys) throws IOException, NoSuchAuthorityCodeException, FactoryException {
    298         logger.debug("resample");
     296    void resample(CoordinateReferenceSystem refSys) throws IOException, FactoryException {
     297        Logging.debug("ImportImagePlugin ImageLayer: resample");
    299298        GridCoverage2D coverage = PluginOperations.createGridFromFile(this.imageFile, refSys, true);
    300299        coverage = PluginOperations.reprojectCoverage(coverage, CRS.decode(ProjectionRegistry.getProjection().toCode()));
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImageFileImporter.java

    r34519 r36013  
    55
    66import java.io.File;
    7 import java.io.IOException;
    87import java.util.List;
    98
    109import javax.swing.JOptionPane;
    1110
    12 import org.apache.log4j.Logger;
    1311import org.openstreetmap.josm.actions.ExtensionFileFilter;
    1412import org.openstreetmap.josm.gui.MainApplication;
     
    1614import org.openstreetmap.josm.gui.progress.ProgressMonitor;
    1715import org.openstreetmap.josm.gui.util.GuiHelper;
    18 import org.openstreetmap.josm.io.IllegalDataException;
    1916import org.openstreetmap.josm.plugins.ImportImagePlugin.ImageLayer.LayerCreationCanceledException;
    2017import org.openstreetmap.josm.tools.Logging;
     
    2522public class ImportImageFileImporter extends FileImporter {
    2623   
    27     private Logger logger = Logger.getLogger(LoadImageAction.class);
    28 
    2924    public ImportImageFileImporter() {
    3025        super(new ExtensionFileFilter("tiff,tif,jpg,jpeg,bmp,png", "jpg",
     
    4338
    4439    @Override
    45     public void importData(List<File> files, ProgressMonitor progressMonitor) throws IOException, IllegalDataException {
     40    public void importData(List<File> files, ProgressMonitor progressMonitor) {
    4641        if (null == files) return;
    4742
    4843        for (File file: files) {
    4944            if (file.isDirectory()) continue;
    50             ImageLayer layer = null;
    51             logger.info("File choosen:" + file);
     45            ImageLayer layer;
     46            Logging.info("ImportImageFileImporter: File chosen: {0}", file);
    5247            try {
    5348                layer = new ImageLayer(file);
    5449            } catch (LayerCreationCanceledException e) {
     50                Logging.trace(e);
    5551                // if user decides that layer should not be created just return.
    5652                continue;
    5753            } catch (Exception e) {
     54                Logging.error("ImportImageFileImporter: Error while creating image layer: \n{0}", e.getMessage());
    5855                Logging.error(e);
    59                 logger.error("Error while creating image layer: \n" + e.getMessage());
    6056                GuiHelper.runInEDT(() ->
    6157                    JOptionPane.showMessageDialog(MainApplication.getMainFrame(), tr("Error while creating image layer: {0}", e.getCause())));
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImagePlugin.java

    r34519 r36013  
    22package org.openstreetmap.josm.plugins.ImportImagePlugin;
    33
     4import java.io.BufferedWriter;
    45import java.io.File;
    5 import java.io.FileWriter;
    66import java.io.IOException;
     7import java.io.InputStream;
    78import java.net.URL;
     9import java.nio.file.Files;
     10import java.nio.file.Paths;
    811import java.util.Properties;
    912
    10 import javax.swing.JMenu;
    11 
    12 import org.apache.log4j.Logger;
    13 import org.apache.log4j.PropertyConfigurator;
    1413import org.openstreetmap.josm.actions.ExtensionFileFilter;
    1514import org.openstreetmap.josm.actions.JosmAction;
     
    1918import org.openstreetmap.josm.plugins.Plugin;
    2019import org.openstreetmap.josm.plugins.PluginInformation;
     20import org.openstreetmap.josm.tools.JosmRuntimeException;
     21import org.openstreetmap.josm.tools.Logging;
    2122import org.openstreetmap.josm.tools.Utils;
    2223
     
    2526 * Provides basic routines for plugin installation and provides the plugin properties.
    2627 *
    27  *
    2828 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny
    2929 *
     
    3131public class ImportImagePlugin extends Plugin {
    3232
    33     private static Logger logger;
    34 
    35     JMenu mainmenu = null;
    36     JosmAction loadFileAction = null;
     33    JosmAction loadFileAction;
    3734
    3835    // plugin properties
     
    4441    static final String PLUGINPROPERTIES_PATH = PLUGIN_DIR + PLUGINPROPERTIES_FILENAME;
    4542    static final String PLUGINLIBRARIES_DIR = PLUGIN_DIR + "lib/";
    46     static final String LOGGING_PROPERTIES_FILEPATH = PLUGIN_DIR + "log4j.properties/";
    4743
    4844    /**
     
    6460
    6561        try {
    66             // Initialize logger
    67             initializeLogger();
    68 
    6962            // Check whether plugin has already been installed. Otherwise install
    7063            checkInstallation();
    7164
    7265            // If resources are available load properties from plugin directory
    73             if (pluginProps == null || pluginProps.isEmpty()) {
    74                 pluginProps = new Properties();
    75                 pluginProps.load(new File(PLUGINPROPERTIES_PATH).toURI().toURL().openStream());
    76                 logger.debug("Plugin properties loaded");
    77             }
     66            loadPluginProps();
    7867
    7968            // load information about supported reference systems
     
    8877
    8978        } catch (IOException e) {
    90             logger.fatal("Error while loading plugin", e);
    91             throw e;
     79            throw new JosmRuntimeException(e);
     80        }
     81    }
     82
     83    private static void loadPluginProps() throws IOException {
     84        if (pluginProps == null || pluginProps.isEmpty()) {
     85            pluginProps = new Properties();
     86            try (InputStream stream = Files.newInputStream(Paths.get(PLUGINPROPERTIES_PATH))) {
     87                pluginProps.load(stream);
     88            }
     89            Logging.debug("ImportImagePlugin: Plugin properties loaded");
    9290        }
    9391    }
     
    9795     * If not, start install procedure.
    9896     */
    99     private void checkInstallation() throws IOException {
     97    private static void checkInstallation() throws IOException {
    10098        // check plugin resource state
    101         boolean isInstalled = true;
    102         if (!new File(PLUGINPROPERTIES_PATH).exists()
    103                 || !new File(PLUGIN_DIR).exists()
    104                 || !new File(PLUGINLIBRARIES_DIR).exists())
    105             isInstalled = false;
     99        boolean isInstalled = new File(PLUGINPROPERTIES_PATH).exists()
     100                && new File(PLUGIN_DIR).exists()
     101                && new File(PLUGINLIBRARIES_DIR).exists();
    106102
    107103
     
    125121            // create local properties file
    126122            if (pluginProps == null || pluginProps.isEmpty()) {
    127                 try (FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH))) {
    128                     URL propertiesURL = getClass().getResource("resources/" + PLUGINPROPERTIES_FILENAME);
     123                try (BufferedWriter fw = Files.newBufferedWriter(Paths.get(PLUGINPROPERTIES_PATH))) {
     124                    URL propertiesURL = ImportImagePlugin.class.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
    129125                    if (propertiesURL != null) {
    130126                        pluginProps = new Properties();
    131                         pluginProps.load(propertiesURL.openStream());
     127                        try (InputStream stream = propertiesURL.openStream()) {
     128                            pluginProps.load(stream);
     129                        }
    132130                        pluginProps.store(fw, null);
    133131                    }
     132
    134133                }
    135                 logger.debug("Plugin properties loaded");
     134                Logging.debug("ImportImagePlugin: Plugin properties loaded");
    136135            }
    137136
    138             if (!new File(LOGGING_PROPERTIES_FILEPATH).exists()) {
    139                 try (FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH))) {
    140                     URL propertiesURL = getClass().getResource("resources/log4j.properties");
    141                     if (propertiesURL != null) {
    142                         Properties loggingProps = new Properties();
    143                         loggingProps.load(propertiesURL.openStream());
    144                         loggingProps.store(fw, null);
    145                     }
    146                 }
    147                 logger.debug("Logging properties created");
    148             }
    149 
    150             logger.debug("Plugin successfully installed");
     137            Logging.debug("ImportImagePlugin: Plugin successfully installed");
    151138        }
    152139    }
    153 
    154     /**
    155      * Initialize logger.
    156      */
    157     private void initializeLogger() {
    158 
    159         Properties props = new Properties();
    160         try {
    161             props.load(new File(LOGGING_PROPERTIES_FILEPATH).toURI().toURL().openStream());
    162 
    163             // Set file for logging here:
    164             props.setProperty("log4j.appender.MyRoFiAppender.file",
    165                     (Preferences.main().getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin/" + "log.log"));
    166 
    167             PropertyConfigurator.configure(props);
    168 
    169             logger = Logger.getLogger(ImportImagePlugin.class);
    170 
    171             logger.info("Logger successfully initialized.");
    172 
    173             return;
    174 
    175         } catch (IOException e) {
    176             System.out.println("Logging properties file not found. Using standard settings.");
    177         }
    178 
    179         // if no log4j.properties file can be found, initialize manually:
    180 
    181         props.setProperty("log4j.rootLogger", "INFO, A");
    182         props.setProperty("log4j.appender.A", "org.apache.log4j.FileAppender");
    183 
    184         props.setProperty("log4j.appender.A.layout",
    185                 "org.apache.log4j.PatternLayout ");
    186         props.setProperty("log4j.appender.A.layout.ConversionPattern",
    187                 "%d{ISO8601} %-5p [%t] %c: %m%n");
    188 
    189         // Set file for logging here:
    190         props.setProperty("log4j.appender.A.file",
    191                 (Preferences.main().getPluginsDirectory().getAbsolutePath() + "/ImportImagePlugin/" + "log.log"));
    192 
    193         PropertyConfigurator.configure(props);
    194         logger = Logger.getLogger(ImportImagePlugin.class);
    195     }
    196140}
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java

    r34445 r36013  
    1010import java.awt.event.KeyAdapter;
    1111import java.awt.event.KeyEvent;
    12 import java.io.File;
    13 import java.io.FileWriter;
     12import java.io.BufferedWriter;
    1413import java.io.IOException;
    15 import java.util.Iterator;
    16 import java.util.Vector;
     14import java.nio.file.Files;
     15import java.nio.file.Paths;
     16import java.util.List;
    1717
    1818import javax.swing.JButton;
     
    3838 * UI-Dialog which provides:
    3939 * - general and spatial information about the georeferenced image
    40  * - a possiblitly to change the source reference system of the image
    41  *
     40 * - a possibility to change the source reference system of the image
    4241 *
    4342 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny
     
    4645public class LayerPropertiesDialog extends JFrame {
    4746
    48     private Vector<String> supportedCRS;
     47    private final List<String> supportedCRS;
    4948    private ImageLayer imageLayer;
    5049
    51     private JPanel mainPanel = null;
    52     private JPanel jPanel = null;
    53     private JPanel buttonPanel = null;
    54     private JTabbedPane jTabbedPane = null;
    55     private JPanel infoPanel = null;
    56     private JPanel crsPanel = null;
    57     private JButton okButton = null;
    58     private JLabel layerNameLabel = null;
    59     private JLabel layerNameValueLabel = null;
    60     private JLabel imageFileLabel = null;
    61     private JLabel imageFileValueLabel = null;
    62     private JLabel sizeLabel = null;
    63     private JLabel sizeValueLabel = null;
    64     private JLabel crsLabel = null;
    65     private JLabel crsValueLabel = null;
    66     private JLabel extentLabel = null;
    67     private JLabel defaultCRSDescriptorLabel = null;
    68     private JLabel defaultCRSLabel = null;
    69     private JTextField searchField = null;
    70     private JScrollPane crsListScrollPane = null;
    71     private JList<String> crsJList = null;
    72     private JButton useDefaultCRSButton = null;
    73     private JButton applySelectedCRSButton = null;
    74     private JButton setSelectedCRSAsDefaultButton = null;
    75     private JLabel searchFieldLabel = null;
    76     private JCheckBox eastingFirstCheckBox = null;
    77     private JLabel eastingFirstLabel = null;
    78     private JLabel tabDescriptionLabel = null;
    79     private JLabel upperLeftLabel = null;
    80     private JLabel lowerLeftLabel = null;
    81     private JLabel upperRightLabel = null;
    82     private JLabel lowerRightLabel = null;
    83     private JLabel upperLeftValueLabel = null;
    84     private JLabel upperRightValueLabel = null;
    85     private JLabel lowerLeftValueLabel = null;
    86     private JLabel lowerRightValueLabel = null;
    87     private JLabel currentCRSLabel = null;
    88     private JLabel currentCRSValueLabel = null;
     50    private JPanel mainPanel;
     51    private JPanel jPanel;
     52    private JPanel buttonPanel;
     53    private JTabbedPane jTabbedPane;
     54    private JPanel infoPanel;
     55    private JPanel crsPanel;
     56    private JButton okButton;
     57    private JLabel defaultCRSLabel;
     58    private JTextField searchField;
     59    private JScrollPane crsListScrollPane;
     60    private JList<String> crsJList;
     61    private JButton useDefaultCRSButton;
     62    private JButton applySelectedCRSButton;
     63    private JButton setSelectedCRSAsDefaultButton;
     64    private JCheckBox eastingFirstCheckBox;
    8965
    9066    /**
     
    9268     *
    9369     */
    94     public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) {
     70    public LayerPropertiesDialog(ImageLayer imageLayer, List<String> supportedCRS) {
    9571        super(imageLayer.getName());
    9672        this.supportedCRS = supportedCRS;
     
    10379     *
    10480     */
    105     public LayerPropertiesDialog(Vector<String> supportedCRS) {
     81    public LayerPropertiesDialog(List<String> supportedCRS) {
    10682        super();
    10783        this.supportedCRS = supportedCRS;
     
    191167    private JPanel getInfoPanel() {
    192168        if (infoPanel == null) {
    193             lowerRightValueLabel = new JLabel();
     169            JLabel lowerRightValueLabel = new JLabel();
    194170            lowerRightValueLabel.setBounds(new Rectangle(210, 315, 134, 16));
    195171            lowerRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    196172            lowerRightValueLabel.setText((float) imageLayer.getBbox().getMinX() + ", " + (float) imageLayer.getBbox().getMaxY());
    197             lowerLeftValueLabel = new JLabel();
     173            JLabel lowerLeftValueLabel = new JLabel();
    198174            lowerLeftValueLabel.setBounds(new Rectangle(30, 315, 133, 16));
    199175            lowerLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);
    200176            lowerLeftValueLabel.setText((float) imageLayer.getBbox().getMinX() + ", " + (float) imageLayer.getBbox().getMinY());
    201             upperRightValueLabel = new JLabel();
     177            JLabel upperRightValueLabel = new JLabel();
    202178            upperRightValueLabel.setBounds(new Rectangle(210, 255, 138, 16));
    203179            upperRightValueLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    204180            upperRightValueLabel.setText((float) imageLayer.getBbox().getMaxX() + ", " + (float) imageLayer.getBbox().getMaxY());
    205             upperLeftValueLabel = new JLabel();
     181            JLabel upperLeftValueLabel = new JLabel();
    206182            upperLeftValueLabel.setBounds(new Rectangle(30, 255, 133, 16));
    207183            upperLeftValueLabel.setHorizontalAlignment(SwingConstants.LEFT);
    208184            upperLeftValueLabel.setText((float) imageLayer.getBbox().getMaxX() + ", " + (float) imageLayer.getBbox().getMinY());
    209             lowerRightLabel = new JLabel();
     185            JLabel lowerRightLabel = new JLabel();
    210186            lowerRightLabel.setBounds(new Rectangle(287, 344, 74, 16));
    211187            lowerRightLabel.setText("Lower Right");
    212             upperRightLabel = new JLabel();
     188            JLabel upperRightLabel = new JLabel();
    213189            upperRightLabel.setBounds(new Rectangle(285, 225, 91, 16));
    214190            upperRightLabel.setText("Upper Right");
    215             lowerLeftLabel = new JLabel();
     191            JLabel lowerLeftLabel = new JLabel();
    216192            lowerLeftLabel.setBounds(new Rectangle(15, 345, 92, 16));
    217193            lowerLeftLabel.setText("Lower Left");
    218             upperLeftLabel = new JLabel();
     194            JLabel upperLeftLabel = new JLabel();
    219195            upperLeftLabel.setBounds(new Rectangle(15, 224, 91, 16));
    220196            upperLeftLabel.setText("Upper Left");
    221             extentLabel = new JLabel();
     197            JLabel extentLabel = new JLabel();
    222198            extentLabel.setBounds(new Rectangle(120, 195, 136, 16));
    223199            extentLabel.setEnabled(false);
     
    225201            extentLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
    226202            extentLabel.setText("Extent");
    227             crsValueLabel = new JLabel();
     203            JLabel crsValueLabel = new JLabel();
    228204            crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16));
    229205
     
    236212            crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")");
    237213
    238             crsLabel = new JLabel();
     214            JLabel crsLabel = new JLabel();
    239215            crsLabel.setBounds(new Rectangle(15, 150, 118, 16));
    240216            crsLabel.setText("Reference System");
    241             sizeValueLabel = new JLabel();
     217            JLabel sizeValueLabel = new JLabel();
    242218            sizeValueLabel.setBounds(new Rectangle(150, 105, 226, 16));
    243219            sizeValueLabel.setText(imageLayer.getImage().getHeight() + " x " + imageLayer.getImage().getWidth());
    244             sizeLabel = new JLabel();
     220            JLabel sizeLabel = new JLabel();
    245221            sizeLabel.setBounds(new Rectangle(15, 105, 121, 16));
    246222            sizeLabel.setText("Image size");
    247             imageFileValueLabel = new JLabel();
     223            JLabel imageFileValueLabel = new JLabel();
    248224            imageFileValueLabel.setBounds(new Rectangle(150, 60, 226, 16));
    249225            imageFileValueLabel.setText(imageLayer.getImageFile().getAbsolutePath());
    250226            imageFileValueLabel.setToolTipText(imageLayer.getImageFile().getAbsolutePath());
    251             imageFileLabel = new JLabel();
     227            JLabel imageFileLabel = new JLabel();
    252228            imageFileLabel.setBounds(new Rectangle(15, 60, 121, 16));
    253229            imageFileLabel.setText("Image file");
    254             layerNameValueLabel = new JLabel();
     230            JLabel layerNameValueLabel = new JLabel();
    255231            layerNameValueLabel.setBounds(new Rectangle(150, 15, 226, 16));
    256232            layerNameValueLabel.setText(imageLayer.getName());
    257             layerNameLabel = new JLabel();
     233            JLabel layerNameLabel = new JLabel();
    258234            layerNameLabel.setBounds(new Rectangle(15, 15, 121, 16));
    259235            layerNameLabel.setText("Layer name");
     
    289265    private JPanel getCrsPanel() {
    290266        if (crsPanel == null) {
    291             currentCRSValueLabel = new JLabel();
     267            JLabel currentCRSValueLabel = new JLabel();
    292268            currentCRSValueLabel.setBounds(new Rectangle(78, 33, 297, 16));
    293269            String crsDescription = "unknown";
     
    299275            currentCRSValueLabel.setText(crsDescription);
    300276
    301             currentCRSLabel = new JLabel();
     277            JLabel currentCRSLabel = new JLabel();
    302278            currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16));
    303279            currentCRSLabel.setText("Current:");
    304             tabDescriptionLabel = new JLabel();
     280            JLabel tabDescriptionLabel = new JLabel();
    305281            tabDescriptionLabel.setBounds(new Rectangle(15, 9, 361, 16));
    306282            tabDescriptionLabel.setText("Set here the source reference system of the image");
    307             eastingFirstLabel = new JLabel();
     283            JLabel eastingFirstLabel = new JLabel();
    308284            eastingFirstLabel.setBounds(new Rectangle(315, 210, 76, 46));
    309285            eastingFirstLabel.setHorizontalTextPosition(SwingConstants.TRAILING);
    310286            eastingFirstLabel.setHorizontalAlignment(SwingConstants.CENTER);
    311287            eastingFirstLabel.setText("<html>Easting<br>first</html>");
    312             searchFieldLabel = new JLabel();
     288            JLabel searchFieldLabel = new JLabel();
    313289            searchFieldLabel.setBounds(new Rectangle(298, 114, 84, 16));
    314290            searchFieldLabel.setDisplayedMnemonic(KeyEvent.VK_UNDEFINED);
     
    319295            defaultCRSLabel.setBounds(new Rectangle(15, 89, 361, 16));
    320296            defaultCRSLabel.setText(PluginOperations.defaultSourceCRSDescription);
    321             defaultCRSDescriptorLabel = new JLabel();
     297            JLabel defaultCRSDescriptorLabel = new JLabel();
    322298            defaultCRSDescriptorLabel.setBounds(new Rectangle(15, 63, 226, 16));
    323299            defaultCRSDescriptorLabel.setText("Default Reference System:");
     
    373349                public void keyTyped(KeyEvent e) {
    374350
    375                     for (Iterator<String> iterator = supportedCRS.iterator(); iterator.hasNext();) {
    376                         String type = iterator.next();
     351                    for (String type : supportedCRS) {
    377352                        if (type.contains(searchField.getText())) {
    378353                            crsJList.setSelectedIndex(supportedCRS.indexOf(type));
     
    409384    private JList<String> getCrsJList() {
    410385        if (crsJList == null) {
    411             crsJList = new JList<>(supportedCRS);
     386            crsJList = new JList<>(supportedCRS.toArray(new String[0]));
    412387            crsJList.addListSelectionListener(new ListSelectionHandler());
    413388        }
     
    497472                                        "" + eastingFirstCheckBox.isSelected());
    498473                                ImportImagePlugin.pluginProps.setProperty("default_crs_srid", code);
    499                                 try (FileWriter fileWriter = new FileWriter(new File(ImportImagePlugin.PLUGINPROPERTIES_PATH))) {
     474                                try (BufferedWriter fileWriter = Files.newBufferedWriter(Paths.get(ImportImagePlugin.PLUGINPROPERTIES_PATH))) {
    500475                                    ImportImagePlugin.pluginProps.store(fileWriter, null);
    501476                                }
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LoadImageAction.java

    r34519 r36013  
    1010import javax.swing.JOptionPane;
    1111
    12 import org.apache.log4j.Logger;
    1312import org.openstreetmap.josm.actions.JosmAction;
    1413import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
     
    1615import org.openstreetmap.josm.plugins.ImportImagePlugin.ImageLayer.LayerCreationCanceledException;
    1716import org.openstreetmap.josm.spi.preferences.Config;
     17import org.openstreetmap.josm.tools.Logging;
    1818
    1919/**
     
    2424 */
    2525public class LoadImageAction extends JosmAction {
    26 
    27     private Logger logger = Logger.getLogger(LoadImageAction.class);
    2826
    2927    /**
     
    4240        int result = fc.showOpenDialog(MainApplication.getMainFrame());
    4341
    44         ImageLayer layer = null;
     42        ImageLayer layer;
    4543        if (result == JFileChooser.APPROVE_OPTION) {
    4644            Config.getPref().put("plugins.importimage.importpath", fc.getCurrentDirectory().getAbsolutePath());
    47             logger.info("File chosen:" + fc.getSelectedFile());
     45            Logging.info("ImportImagePlugin LoadImageAction: File chosen: {0}", fc.getSelectedFile());
    4846            try {
    4947                layer = new ImageLayer(fc.getSelectedFile());
    5048            } catch (LayerCreationCanceledException e) {
     49                Logging.trace(e);
    5150                // if user decides that layer should not be created just return.
    5251                return;
    5352            } catch (Exception e) {
    54                 logger.error("Error while creating image layer: \n" + e.getMessage());
     53                Logging.error("ImportImagePlugin LoadImageAction: Error while creating image layer: \n{0}", e.getMessage());
    5554                JOptionPane.showMessageDialog(null, marktr("Error while creating image layer: " + e.getCause()));
    5655                return;
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java

    r35125 r36013  
    77import java.io.File;
    88import java.io.FileNotFoundException;
    9 import java.io.FileReader;
    109import java.io.IOException;
     10import java.nio.file.Files;
    1111import java.util.Arrays;
    12 import java.util.Iterator;
     12import java.util.List;
    1313import java.util.Properties;
    1414import java.util.Set;
     
    1717import javax.imageio.ImageIO;
    1818
    19 import org.apache.log4j.Logger;
    2019import org.geotools.coverage.grid.GridCoverage2D;
    2120import org.geotools.coverage.grid.GridCoverageFactory;
     
    2928import org.opengis.parameter.ParameterValueGroup;
    3029import org.opengis.referencing.FactoryException;
    31 import org.opengis.referencing.NoSuchAuthorityCodeException;
    3230import org.opengis.referencing.crs.CRSAuthorityFactory;
    3331import org.opengis.referencing.crs.CoordinateReferenceSystem;
    3432import org.opengis.util.InternationalString;
     33import org.openstreetmap.josm.tools.Logging;
    3534
    3635/**
     
    4241public final class PluginOperations {
    4342
    44     private static final Logger logger = Logger.getLogger(PluginOperations.class);
    45 
    4643    // contains descriptions of all available CRS
    47     static Vector<String> crsDescriptions;
     44    static List<String> crsDescriptions;
    4845
    4946    // the standard native CRS of user images
     
    6865     */
    6966    public static GridCoverage2D reprojectCoverage(GridCoverage2D coverage,
    70             CoordinateReferenceSystem targetCrs) throws NoSuchAuthorityCodeException, FactoryException {
     67            CoordinateReferenceSystem targetCrs) {
    7168
    7269        // TODO: add category for NO_DATA values in coverage (transparency in image)
    7370
    74         GridCoverage2D destination = null;
     71        GridCoverage2D destination;
    7572
    7673        CoverageProcessor processor = new CoverageProcessor();
     
    8885
    8986    /**
    90      * Creates a org.geotools.coverage.grid.GridCoverage2D from a given file.
     87     * Creates a {@link GridCoverage2D} from a given file.
     88     * @param file The file to read from
     89     * @param refSys The reference system to use
     90     * @param failIfNoPrjFile {@code true} if we need to fail if no projection file is found
     91     * @throws IOException if the file could not be read
     92     * @return The 2d grid coverage of the file
    9193     */
    9294    public static GridCoverage2D createGridFromFile(File file, CoordinateReferenceSystem refSys, boolean failIfNoPrjFile) throws IOException {
    9395
    94         GridCoverage2D coverage = null;
     96        GridCoverage2D coverage;
    9597
    9698        if (!file.exists()) throw new FileNotFoundException("File not found.");
    9799
    98         String extension = null;
    99         String fileNameWithoutExt = null;
     100        String extension;
     101        String fileNameWithoutExt;
    100102        int dotPos = file.getAbsolutePath().lastIndexOf(".");
    101103        extension = file.getAbsolutePath().substring(dotPos);
     
    103105
    104106        /*------- switch for file type -----------*/
    105         if (extension.equalsIgnoreCase(".tif") || extension.equalsIgnoreCase(".tiff")) {
     107        if (".tif".equalsIgnoreCase(extension) || ".tiff".equalsIgnoreCase(extension)) {
    106108
    107109            // try to read GeoTIFF:
     
    111113            } catch (DataSourceException dse) {
    112114                if (!dse.getMessage().contains("Coordinate Reference System is not available")) {
    113                     dse.printStackTrace();
    114                 }
    115             } catch (FactoryException facte) {
    116                 logger.fatal("Error while reading from GeoTIFF:", facte);
    117                 throw new IOException(facte);
     115                    Logging.error(dse);
     116                } else {
     117                    Logging.trace(dse);
     118                }
    118119            }
    119120
     
    122123            // try to read Worldfile:
    123124            WorldFileReader tfwReader = null;
    124             for (int i = 0; i < postfixes.length; i++) {
    125                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     125            for (String postfix : postfixes) {
     126                File prjFile = new File(fileNameWithoutExt + "." + postfix);
    126127                if (prjFile.exists()) {
    127128                    tfwReader = new WorldFileReader(prjFile);
     
    138139                if (refSys == null) {
    139140                    if (failIfNoPrjFile) throw new IOException("No projection file found.");
    140                     logger.debug("no projection given, no projection file found; using unprojected file.");
     141                    Logging.debug("no projection given, no projection file found; using unprojected file.");
    141142                }
    142143            }
     
    155156            coverage = createGridCoverage(img, bbox, refSys);
    156157
    157         } else if (extension.equalsIgnoreCase(".jpg")
    158                 || extension.equalsIgnoreCase(".jpeg")) {
     158        } else if (".jpg".equalsIgnoreCase(extension)
     159                || ".jpeg".equalsIgnoreCase(extension)) {
    159160            String[] postfixes = {"wld", "jgw", "jpgw"};
    160161            // try to read Worldfile:
    161162            WorldFileReader tfwReader = null;
    162             for (int i = 0; i < postfixes.length; i++) {
    163                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     163            for (String postfix : postfixes) {
     164                File prjFile = new File(fileNameWithoutExt + "." + postfix);
    164165                if (prjFile.exists()) {
    165166                    tfwReader = new WorldFileReader(prjFile);
     
    173174                if (refSys == null) {
    174175                    if (failIfNoPrjFile) throw new IOException("No projection file found.");
    175                     logger.debug("no projection given, no projection file found; using unprojected file.");
     176                    Logging.debug("no projection given, no projection file found; using unprojected file.");
    176177                }
    177178            }
     
    187188            coverage = createGridCoverage(img, bbox, refSys);
    188189
    189         } else if (extension.equalsIgnoreCase(".bmp")) {
     190        } else if (".bmp".equalsIgnoreCase(extension)) {
    190191            String[] postfixes = {"wld", "bmpw", "bpw"};
    191192            // try to read Worldfile:
    192193            WorldFileReader tfwReader = null;
    193             for (int i = 0; i < postfixes.length; i++) {
    194                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     194            for (String postfix : postfixes) {
     195                File prjFile = new File(fileNameWithoutExt + "." + postfix);
    195196                if (prjFile.exists()) {
    196197                    tfwReader = new WorldFileReader(prjFile);
     
    204205                if (refSys == null) {
    205206                    if (failIfNoPrjFile) throw new IOException("No projection file found.");
    206                     logger.debug("no projection given, no projection file found; using unprojected file.");
     207                    Logging.debug("no projection given, no projection file found; using unprojected file.");
    207208                }
    208209            }
     
    218219            coverage = createGridCoverage(img, bbox, refSys);
    219220
    220         } else if (extension.equalsIgnoreCase(".png")) {
     221        } else if (".png".equalsIgnoreCase(extension)) {
    221222
    222223            String[] postfixes = {"wld", "pgw", "pngw"};
    223224            // try to read Worldfile:
    224225            WorldFileReader tfwReader = null;
    225             for (int i = 0; i < postfixes.length; i++) {
    226                 File prjFile = new File(fileNameWithoutExt + "." + postfixes[i]);
     226            for (String postfix : postfixes) {
     227                File prjFile = new File(fileNameWithoutExt + "." + postfix);
    227228                if (prjFile.exists()) {
    228229                    tfwReader = new WorldFileReader(prjFile);
     
    236237                if (refSys == null) {
    237238                    if (failIfNoPrjFile) throw new IOException("No projection file found.");
    238                     logger.debug("no projection given, no projection file found; using unprojected file.");
     239                    Logging.debug("no projection given, no projection file found; using unprojected file.");
    239240                }
    240241            }
     
    265266     */
    266267    public static CoordinateReferenceSystem readPrjFile(File file) throws IOException {
    267         CoordinateReferenceSystem refSys = null;
    268 
    269         String prjFilename = null;
     268        CoordinateReferenceSystem refSys;
     269
     270        String prjFilename;
    270271        int dotPos = file.getAbsolutePath().lastIndexOf(".");
    271272        prjFilename = file.getAbsolutePath().substring(0, dotPos) + ".prj";
     
    273274        File prjFile = new File(prjFilename);
    274275        if (!prjFile.exists()) return null;
    275         logger.debug("Loading .prj file: " + prjFile.getAbsolutePath());
    276 
    277         try (BufferedReader br = new BufferedReader(new FileReader(prjFile))) {
     276        Logging.debug("Loading .prj file: " + prjFile.getAbsolutePath());
     277
     278        try (BufferedReader br = Files.newBufferedReader(prjFile.toPath())) {
    278279            StringBuilder sb = new StringBuilder();
    279             String content = null;
     280            String content;
    280281            while ((content = br.readLine()) != null) {
    281282                sb.append(content);
     
    283284            refSys = CRS.parseWKT(sb.toString().trim());
    284285        } catch (FactoryException e) {
    285             throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'");
     286            throw new IOException("Unable to parse prj-file: '" + prjFile.getName() + "'", e);
    286287        }
    287288
     
    302303     * @param refSys if delivered, the coverage will be forced to use this crs
    303304     */
    304     public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException, FactoryException {
    305         GridCoverage2D coverage = null;
     305    public static GridCoverage2D readGeoTiff(File file, CoordinateReferenceSystem refSys) throws IOException {
     306        GridCoverage2D coverage;
    306307        Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, true);
    307308        if (refSys != null) {
     
    328329        CRSAuthorityFactory fac = CRS.getAuthorityFactory(false);
    329330
    330         for (Iterator<String> iterator = supportedCodes.iterator(); iterator.hasNext();) {
    331             String string = iterator.next();
     331        for (String string : supportedCodes) {
    332332            try {
    333333                if ("WGS84(DD)".equals(string)) {
     
    338338                crsDescriptions.add(description);
    339339                if (defaultcrsString != null && defaultcrsString.equalsIgnoreCase("EPSG:" + string)) {
    340                     boolean isEastingFirst = Boolean.valueOf(pluginProps.getProperty("default_crs_eastingfirst"));
     340                    boolean isEastingFirst = Boolean.parseBoolean(pluginProps.getProperty("default_crs_eastingfirst"));
    341341                    defaultSourceCRS = CRS.decode("EPSG:" + string, isEastingFirst);
    342342                    defaultSourceCRSDescription = description;
     
    344344
    345345            } catch (FactoryException e) {
    346                 logger.error("Error while loading EPSG data: " + e.getMessage());
     346                Logging.error("Error while loading EPSG data: " + e.getMessage());
     347                Logging.error(e);
    347348            }
    348349        }
  • applications/editors/josm/plugins/ImportImagePlugin/test/unit/org/openstreetmap/josm/plugins/ImportImagePlugin/GeoTiffReaderTest.java

    r33864 r36013  
    22package org.openstreetmap.josm.plugins.ImportImagePlugin;
    33
    4 import static org.junit.Assert.assertNotNull;
     4import static org.junit.jupiter.api.Assertions.assertNotNull;
    55
    66import java.io.File;
     
    1515
    1616import org.geotools.coverage.grid.GridCoverage2D;
    17 import org.junit.Rule;
    18 import org.junit.Test;
     17import org.junit.jupiter.api.Test;
     18import org.junit.jupiter.api.Timeout;
    1919import org.openstreetmap.josm.TestUtils;
    20 import org.openstreetmap.josm.testutils.JOSMTestRules;
     20import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    2121import org.openstreetmap.josm.tools.Logging;
    2222
     
    2525 * Data downloaded from <a href="ftp://ftp.remotesensing.org/pub/geotiff/samples">remotesensing.org</a>.
    2626 */
    27 public class GeoTiffReaderTest {
    28 
    29     /**
    30      * Setup test.
    31      */
    32     @Rule
    33     public JOSMTestRules rules = new JOSMTestRules().preferences().timeout(20000);
    34 
     27@BasicPreferences
     28@Timeout(20)
     29class GeoTiffReaderTest {
    3530    @Test
    36     public void testReadGeoTiffFiles() throws IOException {
     31    void testReadGeoTiffFiles() throws IOException {
    3732        for (Path p : listDataFiles("tif")) {
    3833            File file = p.toFile();
     
    4641     * Lists all datasets files matching given extension.
    4742     * @param ext file extension to search for
    48      * @returns List of all datasets files matching given extension
     43     * @return List of all datasets files matching given extension
    4944     * @throws IOException in case of I/O error
    5045     */
  • applications/editors/josm/plugins/ImportImagePlugin/test/unit/org/openstreetmap/josm/plugins/ImportImagePlugin/ImageLayerTest.java

    r33864 r36013  
    22package org.openstreetmap.josm.plugins.ImportImagePlugin;
    33
    4 import static org.junit.Assert.assertEquals;
    5 import static org.junit.Assert.assertTrue;
     4import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertTrue;
    66
    77import java.io.File;
    88import java.io.InputStream;
    99
    10 import org.junit.Rule;
    11 import org.junit.Test;
     10import org.junit.jupiter.api.Test;
     11import org.junit.jupiter.api.extension.RegisterExtension;
    1212import org.openstreetmap.josm.TestUtils;
    1313import org.openstreetmap.josm.gui.MainApplication;
     
    1515import org.openstreetmap.josm.io.OsmReader;
    1616import org.openstreetmap.josm.testutils.JOSMTestRules;
     17import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    1718
    1819/**
     
    2021 * Data downloaded from <a href="ftp://ftp.remotesensing.org/pub/geotiff/samples">remotesensing.org</a>.
    2122 */
    22 public class ImageLayerTest {
     23@BasicPreferences
     24class ImageLayerTest {
    2325
    2426    /**
    2527     * Setup test.
    2628     */
    27     @Rule
    28     public JOSMTestRules rules = new JOSMTestRules().preferences().projection();
     29    @RegisterExtension
     30    static JOSMTestRules rules = new JOSMTestRules().projection();
    2931
    3032    /**
     
    3335     */
    3436    @Test
    35     public void testTicket14894() throws Exception {
     37    void testTicket14894() throws Exception {
    3638        assertTrue(MainApplication.getLayerManager().getLayers().isEmpty());
    3739        // Step 1: add .osm layer
Note: See TracChangeset for help on using the changeset viewer.