Changeset 30738 in osm


Ignore:
Timestamp:
2014-10-19T01:27:04+02:00 (10 years ago)
Author:
donvip
Message:

[josm_plugins] fix java 7 warnings / global usage of try-with-resource

Location:
applications/editors/josm/plugins
Files:
113 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/HouseNumberTaggingTool/src/org/openstreetmap/josm/plugins/housenumbertool/TagDialog.java

    r30737 r30738  
    411411      try {
    412412         path.mkdirs();
    413 
    414          FileOutputStream file = new FileOutputStream(fileName);
    415          ObjectOutputStream o = new ObjectOutputStream(file);
    416          o.writeObject(dto);
    417          o.close();
     413         try (
     414                 FileOutputStream file = new FileOutputStream(fileName);
     415                 ObjectOutputStream o = new ObjectOutputStream(file)
     416         ) {
     417             o.writeObject(dto);
     418         }
    418419      } catch (Exception ex) {
    419420         logger.log(Level.SEVERE, ex.getMessage());
     
    534535   }
    535536
    536    private Dto loadDto() {
    537       Dto dto = new Dto();
    538       File fileName = new File(pluginDir + TagDialog.TEMPLATE_DATA);
    539 
    540       try {
    541 
    542          if (fileName.exists()) {
    543             FileInputStream file = new FileInputStream(fileName);
    544             ObjectInputStream o = new ObjectInputStream(file);
    545 
    546             dto = (Dto) o.readObject();
    547             o.close();
    548          } else {
    549             dto.setCity(selection.get(TagDialog.TAG_ADDR_CITY));
    550             dto.setCountry(selection.get(TagDialog.TAG_ADDR_COUNTRY));
    551             dto.setHousenumber(selection.get(TagDialog.TAG_ADDR_HOUSENUMBER));
    552             dto.setPostcode(selection.get(TagDialog.TAG_ADDR_POSTCODE));
    553             dto.setStreet(selection.get(TagDialog.TAG_ADDR_STREET));
    554             dto.setState(selection.get(TagDialog.TAG_ADDR_STATE));
    555          }
    556       } catch (Exception ex) {
     537    private Dto loadDto() {
     538        Dto dto = new Dto();
     539        File fileName = new File(pluginDir + TagDialog.TEMPLATE_DATA);
     540
     541        try {
     542            if (fileName.exists()) {
     543                try (
     544                                        FileInputStream file = new FileInputStream(fileName);
     545                                        ObjectInputStream o = new ObjectInputStream(file);
     546                ) {
     547                        dto = (Dto) o.readObject();
     548                }
     549            } else {
     550                    dto.setCity(selection.get(TagDialog.TAG_ADDR_CITY));
     551                    dto.setCountry(selection.get(TagDialog.TAG_ADDR_COUNTRY));
     552                    dto.setHousenumber(selection.get(TagDialog.TAG_ADDR_HOUSENUMBER));
     553                    dto.setPostcode(selection.get(TagDialog.TAG_ADDR_POSTCODE));
     554                    dto.setStreet(selection.get(TagDialog.TAG_ADDR_STREET));
     555                    dto.setState(selection.get(TagDialog.TAG_ADDR_STATE));
     556            }
     557        } catch (Exception ex) {
    557558            logger.log(Level.SEVERE, ex.getMessage());
    558559            fileName.delete();
    559       }
    560       return dto;
    561 
    562    }
    563 
    564     class RadioChangeListener implements ItemListener
    565     {
     560        }
     561        return dto;
     562    }
     563
     564    class RadioChangeListener implements ItemListener {
    566565
    567566         @Override
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImagePlugin.java

    r29805 r30738  
    9595            // add menu entries
    9696            //Main.main.menu.fileMenu.insert(loadFileAction, 8);
    97            
     97
    9898            //Main.main.menu.fileMenu.insertSeparator(9);
    99            
     99
    100100            ExtensionFileFilter.importers.add(new ImportImageFileImporter());
    101101
     
    129129
    130130        // if properties file doesn't exist, install plugin
    131         if(!isInstalled)
    132         {
     131        if (!isInstalled) {
    133132
    134133            /*----------- Begin installation ---------------*/
     
    147146
    148147            // create local properties file
    149             if(pluginProps == null || pluginProps.isEmpty()){
    150 
    151                 FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH));
    152                 URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
    153                 pluginProps = new Properties();
    154                 pluginProps.load(propertiesURL.openStream());
    155                 pluginProps.store(fw, null);
    156                 fw.close();
     148            if (pluginProps == null || pluginProps.isEmpty()) {
     149                try (FileWriter fw = new FileWriter(new File(PLUGINPROPERTIES_PATH))) {
     150                        URL propertiesURL = pluginClassLoader.getResource("resources/" + PLUGINPROPERTIES_FILENAME);
     151                        pluginProps = new Properties();
     152                        pluginProps.load(propertiesURL.openStream());
     153                        pluginProps.store(fw, null);
     154                }
    157155                logger.debug("Plugin properties loaded");
    158156            }
    159157
    160             if(!new File(LOGGING_PROPERTIES_FILEPATH).exists())
    161             {
    162                 FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH));
    163                 URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");
    164                 Properties loggingProps = new Properties();
    165                 loggingProps.load(propertiesURL.openStream());
    166                 loggingProps.store(fw, null);
    167                 fw.close();
     158            if (!new File(LOGGING_PROPERTIES_FILEPATH).exists()) {
     159                try (FileWriter fw = new FileWriter(new File(LOGGING_PROPERTIES_FILEPATH))) {
     160                        URL propertiesURL = pluginClassLoader.getResource("resources/log4j.properties");
     161                        Properties loggingProps = new Properties();
     162                        loggingProps.load(propertiesURL.openStream());
     163                        loggingProps.store(fw, null);
     164                }
    168165                logger.debug("Logging properties created");
    169166            }
     
    172169        }
    173170    }
    174 
    175171
    176172    /**
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java

    r30532 r30738  
    3131import org.opengis.referencing.NoSuchAuthorityCodeException;
    3232import org.opengis.referencing.crs.CoordinateReferenceSystem;
     33import org.openstreetmap.josm.Main;
    3334
    3435/**
     
    3637 * - general and spatial information about the georeferenced image
    3738 * - a possiblitly to change the source reference system of the image
    38  * 
    39  * 
     39 *
     40 *
    4041 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny
    4142 *
    4243 */
    4344public class LayerPropertiesDialog extends JFrame{
    44    
     45
    4546    private Vector<String> supportedCRS;
    4647    private ImageLayer imageLayer;
     
    8687
    8788    /**
    88      * This method initializes 
    89      * 
     89     * This method initializes
     90     *
    9091     */
    9192    public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) {
     
    9596        initialize();
    9697    }
    97    
    98     /**
    99      * This method initializes 
    100      * 
     98
     99    /**
     100     * This method initializes
     101     *
    101102     */
    102103    public LayerPropertiesDialog(Vector<String> supportedCRS) {
     
    105106        initialize();
    106107    }
    107    
     108
    108109
    109110    /**
    110111     * This method initializes this
    111      * 
     112     *
    112113     */
    113114    private void initialize() {
     
    115116        this.setContentPane(getMainPanel());
    116117        this.setPreferredSize(new Dimension(404, 485));
    117            
    118     }
    119 
    120     /**
    121      * This method initializes mainPanel   
    122      * 
    123      * @return javax.swing.JPanel   
     118
     119    }
     120
     121    /**
     122     * This method initializes mainPanel
     123     *
     124     * @return javax.swing.JPanel
    124125     */
    125126    private JPanel getMainPanel() {
     
    134135
    135136    /**
    136      * This method initializes jPanel   
    137      * 
    138      * @return javax.swing.JPanel   
     137     * This method initializes jPanel
     138     *
     139     * @return javax.swing.JPanel
    139140     */
    140141    private JPanel getJPanel() {
     
    155156
    156157    /**
    157      * This method initializes buttonPanel 
    158      * 
    159      * @return javax.swing.JPanel   
     158     * This method initializes buttonPanel
     159     *
     160     * @return javax.swing.JPanel
    160161     */
    161162    private JPanel getButtonPanel() {
     
    170171
    171172    /**
    172      * This method initializes jTabbedPane 
    173      * 
    174      * @return javax.swing.JTabbedPane 
     173     * This method initializes jTabbedPane
     174     *
     175     * @return javax.swing.JTabbedPane
    175176     */
    176177    private JTabbedPane getJTabbedPane() {
     
    184185
    185186    /**
    186      * This method initializes infoPanel   
    187      * 
    188      * @return javax.swing.JPanel   
     187     * This method initializes infoPanel
     188     *
     189     * @return javax.swing.JPanel
    189190     */
    190191    private JPanel getInfoPanel() {
     
    226227            crsValueLabel = new JLabel();
    227228            crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16));
    228            
     229
    229230            String crsDescription = "";
    230231            try {
     
    233234            }
    234235            crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")");
    235            
     236
    236237            crsLabel = new JLabel();
    237238            crsLabel.setBounds(new Rectangle(15, 150, 118, 16));
     
    281282
    282283    /**
    283      * This method initializes crsPanel 
    284      * 
    285      * @return javax.swing.JPanel   
     284     * This method initializes crsPanel
     285     *
     286     * @return javax.swing.JPanel
    286287     */
    287288    private JPanel getCrsPanel() {
     
    295296            }
    296297            currentCRSValueLabel.setText(crsDescription);
    297            
     298
    298299            currentCRSLabel = new JLabel();
    299300            currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16));
     
    339340
    340341    /**
    341      * This method initializes okButton 
    342      * 
    343      * @return javax.swing.JButton 
     342     * This method initializes okButton
     343     *
     344     * @return javax.swing.JButton
    344345     */
    345346    private JButton getOkButton() {
     
    349350            okButton.setText("OK");
    350351            okButton.addActionListener(new java.awt.event.ActionListener() {
    351                 public void actionPerformed(java.awt.event.ActionEvent e) {
    352                    
     352                @Override
     353                                public void actionPerformed(java.awt.event.ActionEvent e) {
     354
    353355                    setVisible(false);
    354356                    dispose();
     
    360362
    361363    /**
    362      * This method initializes searchField 
    363      * 
    364      * @return javax.swing.JTextField   
     364     * This method initializes searchField
     365     *
     366     * @return javax.swing.JTextField
    365367     */
    366368    private JTextField getSearchField() {
     
    370372            searchField.setToolTipText("Enter keywords or EPSG codes");
    371373            searchField.addKeyListener(new java.awt.event.KeyAdapter() {
    372                 public void keyTyped(java.awt.event.KeyEvent e) {
    373                    
     374                @Override
     375                                public void keyTyped(java.awt.event.KeyEvent e) {
     376
    374377                    for (Iterator<String> iterator = supportedCRS.iterator(); iterator.hasNext();) {
    375                         String type = (String) iterator.next();
     378                        String type = iterator.next();
    376379                        if (type.contains(searchField.getText())) {
    377380                            crsJList.setSelectedIndex(supportedCRS.indexOf(type));
     
    379382                            break;
    380383                        }
    381                        
     384
    382385                    }
    383386                }
     
    388391
    389392    /**
    390      * This method initializes crsListScrollPane   
    391      * 
    392      * @return javax.swing.JScrollPane 
     393     * This method initializes crsListScrollPane
     394     *
     395     * @return javax.swing.JScrollPane
    393396     */
    394397    private JScrollPane getCrsListScrollPane() {
     
    402405
    403406    /**
    404      * This method initializes crsJList 
    405      * 
    406      * @return javax.swing.JList   
     407     * This method initializes crsJList
     408     *
     409     * @return javax.swing.JList
    407410     */
    408411    private JList<String> getCrsJList() {
     
    415418
    416419    /**
    417      * This method initializes useDefaultCRSButton 
    418      * 
    419      * @return javax.swing.JButton 
     420     * This method initializes useDefaultCRSButton
     421     *
     422     * @return javax.swing.JButton
    420423     */
    421424    private JButton getUseDefaultCRSButton() {
     
    425428            useDefaultCRSButton.setText("Apply Default");
    426429            useDefaultCRSButton.addActionListener(new java.awt.event.ActionListener() {
    427                 public void actionPerformed(java.awt.event.ActionEvent e) {
    428                    
     430                @Override
     431                                public void actionPerformed(java.awt.event.ActionEvent e) {
     432
    429433                    try {
    430                        
     434
    431435                        setCursor(new Cursor(Cursor.WAIT_CURSOR));
    432436                        if(PluginOperations.defaultSourceCRS != null){
     
    436440                            JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>");
    437441                        }
    438                        
     442
    439443                    } catch (NoSuchAuthorityCodeException e1) {
    440444                        // TODO Auto-generated catch block
     
    457461
    458462    /**
    459      * This method initializes applySelectedCRSButton   
    460      * 
    461      * @return javax.swing.JButton 
     463     * This method initializes applySelectedCRSButton
     464     *
     465     * @return javax.swing.JButton
    462466     */
    463467    private JButton getApplySelectedCRSButton() {
     
    469473            applySelectedCRSButton.setText("<html>Apply<br>Selection</html>");
    470474            applySelectedCRSButton.addActionListener(new java.awt.event.ActionListener() {
    471                 public void actionPerformed(java.awt.event.ActionEvent e) {
    472                    
    473                     String selection = (String) crsJList.getSelectedValue();
     475                @Override
     476                                public void actionPerformed(java.awt.event.ActionEvent e) {
     477
     478                    String selection = crsJList.getSelectedValue();
    474479                    String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
    475                    
     480
    476481                    CoordinateReferenceSystem newRefSys = null;
    477482                    try {
    478483                        newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected());
    479                        
     484
    480485                        setCursor(new Cursor(Cursor.WAIT_CURSOR));
    481                        
     486
    482487                        imageLayer.resample(newRefSys);
    483488
     
    495500                        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    496501                    }
    497                    
    498                    
     502
     503
    499504                }
    500505            });
     
    504509
    505510    /**
    506      * This method initializes setSelectedCRSAsDefaultButton   
    507      * 
    508      * @return javax.swing.JButton 
     511     * This method initializes setSelectedCRSAsDefaultButton
     512     *
     513     * @return javax.swing.JButton
    509514     */
    510515    private JButton getSetSelectedCRSAsDefaultButton() {
     
    515520            setSelectedCRSAsDefaultButton
    516521                    .addActionListener(new java.awt.event.ActionListener() {
    517                         public void actionPerformed(java.awt.event.ActionEvent e) {
    518                            
     522                        @Override
     523                                                public void actionPerformed(java.awt.event.ActionEvent e) {
     524
    519525                            if(crsJList.getSelectedValue() != null){
    520                                 String selection = (String) crsJList.getSelectedValue();
     526                                String selection = crsJList.getSelectedValue();
    521527                                String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]"));
    522                                
     528
    523529                                try {
    524530                                    PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected());
    525531                                    PluginOperations.defaultSourceCRSDescription = selection;
    526                                    
     532
    527533                                    ImportImagePlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected());
    528534                                    ImportImagePlugin.pluginProps.setProperty("default_crs_srid", code);
    529                                     FileWriter fileWriter = new FileWriter(new File(ImportImagePlugin.PLUGINPROPERTIES_PATH));
    530                                     ImportImagePlugin.pluginProps.store(fileWriter, null);
    531                                     fileWriter.close();
    532                                    
     535                                    try (FileWriter fileWriter = new FileWriter(new File(ImportImagePlugin.PLUGINPROPERTIES_PATH))) {
     536                                        ImportImagePlugin.pluginProps.store(fileWriter, null);
     537                                    }
     538
    533539                                    defaultCRSLabel.setText(selection);
    534                                    
    535                                 } catch (IOException e2) {
    536                                     // TODO Auto-generated catch block
    537                                     e2.printStackTrace();
    538                                 } catch (NoSuchAuthorityCodeException e3) {
    539                                     // TODO Auto-generated catch block
    540                                     e3.printStackTrace();
    541                                 } catch (FactoryException e4) {
    542                                     // TODO Auto-generated catch block
    543                                     e4.printStackTrace();
     540
     541                                } catch (IOException | FactoryException e2) {
     542                                    Main.error(e2);
    544543                                }
    545                             }else{
     544                            } else {
    546545                                JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list.");
    547546                            }
    548 
    549                            
    550547                        }
    551548                    });
     
    553550        return setSelectedCRSAsDefaultButton;
    554551    }
    555    
    556     /**
    557      * This method initializes eastingFirstCheckBox 
    558      * 
    559      * @return javax.swing.JCheckBox   
     552
     553    /**
     554     * This method initializes eastingFirstCheckBox
     555     *
     556     * @return javax.swing.JCheckBox
    560557     */
    561558    private JCheckBox getEastingFirstCheckBox() {
     
    568565    }
    569566
    570    
    571    
     567
     568
    572569    /**
    573570     * Listener setting text in the search field if selection has changed.
     
    575572     */
    576573    class ListSelectionHandler implements ListSelectionListener {
    577         public void valueChanged(ListSelectionEvent e) {
     574        @Override
     575                public void valueChanged(ListSelectionEvent e) {
    578576            if(e.getValueIsAdjusting())
    579577            {
  • applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java

    r30737 r30738  
    296296        logger.debug("Loading .prj file: " + prjFile.getAbsolutePath());
    297297
    298         StringBuilder sb = new StringBuilder();
    299         String content = null;
    300         BufferedReader br = new BufferedReader(new FileReader(prjFile));
    301         while((content = br.readLine()) != null)
    302         {
    303             sb.append(content);
    304         }
    305         br.close();
    306         try {
     298        try (BufferedReader br = new BufferedReader(new FileReader(prjFile))) {
     299            StringBuilder sb = new StringBuilder();
     300            String content = null;
     301            while((content = br.readLine()) != null) {
     302                sb.append(content);
     303            }
    307304            refSys = CRS.parseWKT(sb.toString().trim());
    308305        } catch (FactoryException e) {
  • applications/editors/josm/plugins/NanoLog/src/nanolog/NanoLogLayer.java

    r30737 r30738  
    103103        final SimpleDateFormat fmt = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SS");
    104104        List<NanoLogEntry> result = new ArrayList<>();
    105         BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
    106         while( r.ready() ) {
    107             String line = r.readLine();
    108             if( line != null ) {
    109                 Matcher m = NANOLOG_LINE.matcher(line);
    110                 if( m.matches() ) {
    111                     String time = m.group(1);
    112                     String message = m.group(2);
    113                     String lat = m.group(3);
    114                     String lon = m.group(4);
    115                     String dir = m.group(5);
    116                     Date timeDate = null;
    117                     try {
    118                         timeDate = fmt.parse(time);
    119                     } catch( ParseException e ) {
    120                     }
    121                     if( message == null || message.length() == 0 || timeDate == null )
    122                         continue;
    123                     LatLon pos = null;
    124                     Integer direction = null;
    125                     if( lat != null && lon != null ) {
    126                         try {
    127                             pos = new LatLon(Double.parseDouble(lat), Double.parseDouble(lon));
    128                             direction = new Integer(dir);
    129                         } catch( NumberFormatException e ) {
    130                             // well...
    131                         }
    132                     }
    133                     NanoLogEntry entry = new NanoLogEntry(timeDate, message, pos, direction);
    134                     result.add(entry);
    135                 }
    136             }
    137         }
    138         r.close();
     105        try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"))) {
     106                while( r.ready() ) {
     107                    String line = r.readLine();
     108                    if( line != null ) {
     109                        Matcher m = NANOLOG_LINE.matcher(line);
     110                        if( m.matches() ) {
     111                            String time = m.group(1);
     112                            String message = m.group(2);
     113                            String lat = m.group(3);
     114                            String lon = m.group(4);
     115                            String dir = m.group(5);
     116                            Date timeDate = null;
     117                            try {
     118                                timeDate = fmt.parse(time);
     119                            } catch( ParseException e ) {
     120                            }
     121                            if( message == null || message.length() == 0 || timeDate == null )
     122                                continue;
     123                            LatLon pos = null;
     124                            Integer direction = null;
     125                            if( lat != null && lon != null ) {
     126                                try {
     127                                    pos = new LatLon(Double.parseDouble(lat), Double.parseDouble(lon));
     128                                    direction = new Integer(dir);
     129                                } catch( NumberFormatException e ) {
     130                                    // well...
     131                                }
     132                            }
     133                            NanoLogEntry entry = new NanoLogEntry(timeDate, message, pos, direction);
     134                            result.add(entry);
     135                        }
     136                    }
     137                }
     138        }
    139139        return result;
    140140    }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java

    r30737 r30738  
    11// License: GPL. v2 and later. Copyright 2008-2009 by Pieren <pieren3@gmail.com> and others
    22package cadastre_fr;
     3
     4import static org.openstreetmap.josm.tools.I18n.tr;
     5
     6import java.io.BufferedOutputStream;
     7import java.io.File;
     8import java.io.FileInputStream;
     9import java.io.FileOutputStream;
     10import java.io.IOException;
     11import java.io.ObjectInputStream;
     12import java.io.ObjectOutputStream;
     13import java.io.OutputStream;
     14import java.util.ArrayList;
     15import java.util.concurrent.locks.Lock;
     16import java.util.concurrent.locks.ReentrantLock;
     17
     18import javax.swing.JDialog;
     19import javax.swing.JOptionPane;
     20
     21import org.openstreetmap.josm.Main;
     22
    323/**
    424 * This class handles the WMS layer cache mechanism. The design is oriented for a good performance (no
     
    1030 * is inserted before each append and an exception is raised at objects read).
    1131 */
    12 
    13 import static org.openstreetmap.josm.tools.I18n.tr;
    14 
    15 import java.io.*;
    16 import java.util.ArrayList;
    17 import java.util.concurrent.locks.Lock;
    18 import java.util.concurrent.locks.ReentrantLock;
    19 
    20 import javax.swing.JDialog;
    21 import javax.swing.JOptionPane;
    22 import org.openstreetmap.josm.Main;
    23 
    2432public class CacheControl implements Runnable {
    2533
     
    3240            super(out);
    3341        }
     42        @Override
    3443        protected void writeStreamHeader() throws IOException {
    3544            reset();
     
    4049
    4150    public static int cacheSize = 500;
    42 
    4351
    4452    public WMSLayer wmsLayer = null;
     
    141149    public boolean loadCache(File file, int currentLambertZone) {
    142150        boolean successfulRead = false;
    143         FileInputStream fis = null;
    144         ObjectInputStream ois = null;
    145         try {
    146             fis = new FileInputStream(file);
    147             ois = new ObjectInputStream(fis);
     151        try (
     152            FileInputStream fis = new FileInputStream(file);
     153            ObjectInputStream ois = new ObjectInputStream(fis);
     154        ) {
    148155            successfulRead = wmsLayer.read(file, ois, currentLambertZone);
    149156        } catch (Exception ex) {
     
    151158            JOptionPane.showMessageDialog(Main.parent, tr("Error loading file.\nProbably an old version of the cache file."), tr("Error"), JOptionPane.ERROR_MESSAGE);
    152159            return false;
    153         } finally {
    154             try {
    155                 ois.close();
    156                 fis.close();
    157             } catch (Exception e) {
    158                 e.printStackTrace();
    159             }
    160160        }
    161161        if (successfulRead && wmsLayer.isRaster()) {
     
    165165        return successfulRead;
    166166    }
    167 
    168167
    169168    public synchronized void saveCache(GeorefImage image) {
     
    177176     * Thread saving the grabbed images in background.
    178177     */
     178    @Override
    179179    public synchronized void run() {
    180180        for (;;) {
     
    186186                try {
    187187                    if (file.exists()) {
    188                         ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
    189                                 new BufferedOutputStream(new FileOutputStream(file, true)));
    190                         for (int i=0; i < size; i++) {
    191                             oos.writeObject(imagesToSave.get(i));
     188                        try (ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
     189                                new BufferedOutputStream(new FileOutputStream(file, true)))) {
     190                            for (int i=0; i < size; i++) {
     191                                oos.writeObject(imagesToSave.get(i));
     192                            }
    192193                        }
    193                         oos.close();
    194194                    } else {
    195                         ObjectOutputStream oos = new ObjectOutputStream(
    196                                 new BufferedOutputStream(new FileOutputStream(file)));
    197                         wmsLayer.write(file, oos);
    198                         for (int i=0; i < size; i++) {
    199                             oos.writeObject(imagesToSave.get(i));
     195                        try (ObjectOutputStream oos = new ObjectOutputStream(
     196                                new BufferedOutputStream(new FileOutputStream(file)))) {
     197                            wmsLayer.write(file, oos);
     198                            for (int i=0; i < size; i++) {
     199                                oos.writeObject(imagesToSave.get(i));
     200                            }
    200201                        }
    201                         oos.close();
    202202                    }
    203203                } catch (IOException e) {
    204                     e.printStackTrace(System.out);
     204                    Main.error(e);
    205205                }
    206206                imagesLock.lock();
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java

    r28961 r30738  
    2222    private CadastreInterface wmsInterface = new CadastreInterface();
    2323
    24     public GeorefImage grab(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws IOException, OsmTransferException {
    25 
     24    public GeorefImage grab(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax)
     25            throws IOException, OsmTransferException {
    2626        try {
    2727            URL url = null;
     
    8888        wmsInterface.urlConn.setRequestMethod("GET");
    8989        wmsInterface.setCookie();
    90         InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
    91         BufferedImage img = ImageIO.read(is);
    92         is.close();
    93         return img;
     90        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
     91            return ImageIO.read(is);
     92        }
    9493    }
    9594
     
    9796        return wmsInterface;
    9897    }
    99 
    10098}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java

    r30737 r30738  
    229229            }
    230230            if (Main.isDebugEnabled()) {
    231                 Main.debug(lines);
     231                Main.debug(lines);
    232232            }
    233233        } catch (MalformedURLException e) {
     
    284284            urlConn.setDoInput(true);
    285285            setCookie();
    286             OutputStream wr = urlConn.getOutputStream();
    287             wr.write(content.getBytes());
    288             System.out.println("POST "+content);
    289             wr.flush();
    290             wr.close();
    291             BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    292             while ((ln = rd.readLine()) != null) {
    293                 lines += ln;
    294             }
    295             rd.close();
     286            try (OutputStream wr = urlConn.getOutputStream()) {
     287                wr.write(content.getBytes());
     288                Main.info("POST "+content);
     289                wr.flush();
     290            }
     291            try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
     292                while ((ln = rd.readLine()) != null) {
     293                    lines += ln;
     294                }
     295            }
    296296            urlConn.disconnect();
    297297            if (lines != null) {
     
    371371            setCookie(urlConn2);
    372372            urlConn2.connect();
    373             System.out.println("GET "+getAllImagesURL);
    374             BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream()));
    375             while ((ln = rd.readLine()) != null) {
    376                 lines += ln;
    377             }
    378             rd.close();
     373            Main.info("GET "+getAllImagesURL);
     374            try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream()))) {
     375                while ((ln = rd.readLine()) != null) {
     376                    lines += ln;
     377                }
     378            }
    379379            urlConn2.disconnect();
    380             //System.out.println("GET="+lines);
    381380        } catch (IOException e) {
    382381            listOfFeuilles.clear();
    383             e.printStackTrace();
     382            Main.error(e);
    384383        }
    385384        return lines;
     
    483482        }
    484483        System.out.println("GET "+searchFormURL);
    485         BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    486         while ((ln = in.readLine()) != null) {
    487             line += ln;
    488         }
    489         in.close();
     484        try (BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
     485            while ((ln = in.readLine()) != null) {
     486                line += ln;
     487            }
     488        }
    490489        urlConn.disconnect();
    491490        parseBBoxCommune(wmsLayer, line);
     
    511510
    512511    private void parseGeoreferences(WMSLayer wmsLayer, String input) {
    513         /* commented since cadastre WMS changes mid july 2013 
     512        /* commented since cadastre WMS changes mid july 2013
    514513         * until new GeoBox coordinates parsing is solved */
    515514//        if (input.lastIndexOf(cBBoxCommunStart) != -1) {
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionExporter.java

    r29922 r30738  
    3030    }
    3131
    32         @Override
    33         public Collection<Layer> getDependencies() {
     32    @Override
     33    public Collection<Layer> getDependencies() {
    3434        return Collections.emptySet();
    35         }
     35    }
    3636
    37         @Override
    38         public Component getExportPanel() {
     37    @Override
     38    public Component getExportPanel() {
    3939        final JPanel p = new JPanel(new GridBagLayout());
    4040        export = new JCheckBox();
     
    4646        p.add(GBC.glue(1,0), GBC.std().fill(GBC.HORIZONTAL));
    4747        return p;
    48         }
     48    }
    4949
    50         @Override
    51         public boolean shallExport() {
     50    @Override
     51    public boolean shallExport() {
    5252        return export.isSelected();
    53         }
     53    }
    5454
    55         @Override
    56         public boolean requiresZip() {
    57                 return false;
    58         }
     55    @Override
     56    public boolean requiresZip() {
     57        return false;
     58    }
    5959
    60         @Override
    61         public Element export(ExportSupport support) throws IOException {
     60    @Override
     61    public Element export(ExportSupport support) throws IOException {
    6262        Element layerEl = support.createElement("layer");
    6363        layerEl.setAttribute("type", "cadastre-fr");
     
    7676        file.appendChild(support.createTextNode(url.toString()));
    7777        return layerEl;
    78         }
     78    }
    7979
    8080}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionImporter.java

    r30701 r30738  
    2222public class CadastreSessionImporter implements SessionLayerImporter{
    2323
    24         @Override
    25         public Layer load(Element elem, ImportSupport support,
    26                         ProgressMonitor progressMonitor) throws IOException,
    27                         IllegalDataException {
     24    @Override
     25    public Layer load(Element elem, ImportSupport support,
     26            ProgressMonitor progressMonitor) throws IOException,
     27            IllegalDataException {
    2828        String version = elem.getAttribute("version");
    2929        if (!"0.1".equals(version)) {
     
    4141            fileStr = URLDecoder.decode(fileStr, "UTF-8");
    4242            fileStr = fileStr.substring(fileStr.indexOf(":/")+2);
    43                 String filename = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
     43            String filename = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
    4444            String ext = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length());
    4545            // create layer and load cache
     
    6060            throw new RuntimeException(e);
    6161        }
    62         }
     62    }
    6363
    6464}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java

    r30737 r30738  
    4343    private static String errorMessage;
    4444
    45 
     45    /**
     46     * Constructs a new {@code DownloadSVGBuilding}.
     47     */
    4648    public DownloadSVGBuilding(WMSLayer wmsLayer) {
    4749        super(tr("Downloading {0}", wmsLayer.getName()));
     
    240242        wmsInterface.urlConn.setRequestMethod("GET");
    241243        wmsInterface.setCookie();
    242         InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
    243244        File file = new File(CadastrePlugin.cacheDir + "building.svg");
    244245        String svg = new String();
    245         try {
     246        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
    246247            if (file.exists())
    247248                file.delete();
    248             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
    249             InputStreamReader isr =new InputStreamReader(is);
    250             BufferedReader br = new BufferedReader(isr);
    251             String line="";
    252             while ( null!=(line=br.readLine())){
    253                 line += "\n";
    254                 bos.write(line.getBytes());
    255                 svg += line;
    256             }
    257             br.close();
    258             bos.close();
     249            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
     250                 InputStreamReader isr = new InputStreamReader(is);
     251                 BufferedReader br = new BufferedReader(isr)) {
     252                String line="";
     253                while ( null!=(line=br.readLine())){
     254                    line += "\n";
     255                    bos.write(line.getBytes());
     256                    svg += line;
     257                }
     258            }
    259259        } catch (IOException e) {
    260             e.printStackTrace(System.out);
    261         }
    262         is.close();
     260            Main.error(e);
     261        }
    263262        return svg;
    264263    }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java

    r30737 r30738  
    4747    private static String errorMessage;
    4848
     49    /**
     50     * Constructs a new {@code DownloadSVGTask}.
     51     */
    4952    public DownloadSVGTask(WMSLayer wmsLayer) {
    5053        super(tr("Downloading {0}", wmsLayer.getName()));
     
    194197        wmsInterface.urlConn.setRequestMethod("GET");
    195198        wmsInterface.setCookie();
    196         InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
    197199        File file = new File(CadastrePlugin.cacheDir + "boundary.svg");
    198200        String svg = new String();
    199         try {
     201        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
    200202            if (file.exists())
    201203                file.delete();
    202             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
    203             InputStreamReader isr =new InputStreamReader(is);
    204             BufferedReader br = new BufferedReader(isr);
    205             String line="";
    206             while ( null!=(line=br.readLine())){
    207                 line += "\n";
    208                 bos.write(line.getBytes());
    209                 svg += line;
     204            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
     205                 InputStreamReader isr =new InputStreamReader(is);
     206                 BufferedReader br = new BufferedReader(isr)) {
     207                String line="";
     208                while ( null!=(line=br.readLine())){
     209                    line += "\n";
     210                    bos.write(line.getBytes());
     211                    svg += line;
     212                }
    210213            }
    211             br.close();
    212             bos.close();
    213214        } catch (IOException e) {
    214             e.printStackTrace(System.out);
    215         }
    216         is.close();
     215            Main.error(e);
     216        }
    217217        return svg;
    218218    }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java

    r30737 r30738  
    133133        // if the layer is currently saving the images in the cache, wait until it's finished
    134134        if(grabThread != null)
    135                         grabThread.cancel();
     135                grabThread.cancel();
    136136        grabThread = null;
    137137        super.destroy();
  • applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanVecTile.java

    r30737 r30738  
    2323
    2424public class CanVecTile {
    25         CanvecLayer layer;
    26         public boolean can_download = false;
    27         private ArrayList<String> sub_tile_ids = new ArrayList<>();
    28         private boolean zip_scanned = false;
    29        
    30         private ArrayList<CanVecTile> sub_tiles = new ArrayList<>();
    31         private boolean sub_tiles_made = false;
    32 
    33         private ArrayList<String> index;
    34         private int depth;
    35        
    36         int corda,cordc;
    37         private boolean valid = false;
    38         String cordb,cordd;
    39         private Bounds bounds;
    40         public String tileid;
    41         public CanVecTile(String tileid,CanvecLayer layer) {
    42                 String parta,partb,partc,partd;
    43                 parta = tileid.substring(0,3);
    44                 partb = tileid.substring(3, 4);
    45                 partc = tileid.substring(4, 6);
    46                 partd = tileid.substring(6);
    47                 int a,c;
    48                 a = Integer.parseInt(parta);
    49                 c = Integer.parseInt(partc);
    50                 real_init(a,partb,c,partd,layer,new ArrayList<String>());
    51         }
    52         public CanVecTile(int a,String b,int c,String d,CanvecLayer layer,ArrayList<String> index) {
    53                 real_init(a,b,c,d,layer,index);
    54         }
    55         public void real_init(int a,String b,int c,String d,CanvecLayer layer, ArrayList<String> index) {
    56                 this.index = index;
    57                 this.layer = layer;
    58                 corda = a;
    59                 cordb = b;
    60                 cordc = c;
    61                 cordd = d;
    62                 double zero_point_lat,zero_point_lon;
    63                 double lat_span,lon_span;
    64                 double lat2,lon2;
    65                 if ((a >= 0) && (a <= 119)) { // main block of tiles
    66                         int column = a / 10;
    67                         int row = a % 10;
    68                         if (row > 6) {
    69                                 // cant handle x7 x8 and x9 yet
    70                                 return;
    71                         }
    72                         zero_point_lat = 40 + 4 * row;
    73                         zero_point_lon = -56 - 8 * column;
    74                
    75                         // size of each grid
    76                         if (row <= 6) {
    77                                 // each is 4x8 degrees, broken into a 4x4 grid
    78                                 lat_span = 4;
    79                                 lon_span = 8;
    80                                 depth = 1;
    81                         } else {
    82                                 return;
    83                         }
    84                 } else { // last few tiles, very far north
    85                         return;
    86                 }
    87 
    88                 // a 4x4 grid of A thru P
    89                 // map A-P to 1-16
    90                 int grid2;
    91                 if (b == "") grid2 = 0;
    92                 else grid2 = b.charAt(0) - 64;
    93                 int rows1[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
    94                 int cols1[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
    95                 lat2 = zero_point_lat + (lat_span/4)*rows1[grid2];
    96                 lon2 = zero_point_lon + (lon_span/4)*cols1[grid2];
    97 
    98                 if (grid2 != 0) {
    99                         lat_span = lat_span / 4;
    100                         lon_span = lon_span / 4;
    101                         depth = 2;
    102                 }
    103 
    104                 int rows3[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
    105                 lat2 = lat2 + (lat_span/4)*rows3[c];
    106                 int cols3[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
    107                 lon2 = lon2 + (lon_span/4)*cols3[c];
    108 
    109                 if (c != 0) {
    110                         lat_span = lat_span / 4;
    111                         lon_span = lon_span / 4;
    112                         depth = 3;
    113                 }
    114                
    115                 if (cordd != "") {
    116                         depth = 4;
    117                         System.out.println("cordd: "+cordd);
    118                         String foo[] = cordd.split("\\.");
    119                         for (int i = 0; i < foo.length; i++) {
    120                                 int cell;
    121                                 System.out.println(foo[i]);
    122                                 if (foo[i] == "osm") break;
    123                                 if (foo[i] == "") continue;
    124                                 try {
    125                                         cell = Integer.parseInt(foo[i]);
    126                                 } catch (NumberFormatException e) {
    127                                         continue;
    128                                 }
    129                                 switch (cell) {
    130                                 case 0:
    131                                         break;
    132                                 case 1:
    133                                         lat2 = lat2 + lat_span/2;
    134                                         break;
    135                                 case 2:
    136                                         lat2 = lat2 + lat_span/2;
    137                                         lon2 = lon2 + lon_span/2;
    138                                         break;
    139                                 case 3:
    140                                         lon2 = lon2 + lon_span/2;
    141                                         break;
    142                                 }
    143                                 lat_span = lat_span/2;
    144                                 lon_span = lon_span/2;
    145                         }
    146                 }
    147 
    148                 bounds = new Bounds(lat2,lon2,lat2+lat_span,lon2+lon_span);
    149                 if (cordb == "") this.tileid = String.format("%03d",corda);
    150                 else if (cordc == 0) this.tileid = String.format("%03d%s",corda,cordb);
    151                 else if (cordd == "") this.tileid = String.format("%03d%s%02d",corda,cordb,cordc);
    152                 else this.tileid = String.format("%03d%s%02d%s",corda,cordb,cordc,cordd);
    153                 valid = true;
    154                 //debug(index.toString());
    155                 //debug("creating tileid: "+this.tileid);
    156         }
    157         public boolean isValid() { return valid; }
    158         public String getTileId() {
    159                 return this.tileid;
    160         }
    161         private void debug(String line) {
    162                 System.out.println(depth + "_" + tileid + ": " + line);
    163         }
    164         public boolean isVisible(Bounds view) {
    165                 return view.intersects(bounds);
    166         }
    167         public Point[] getCorners(MapView mv) {
    168                 LatLon min = bounds.getMin();
    169                 LatLon max = bounds.getMax();
    170                 LatLon x1 = new LatLon(min.lat(),max.lon());
    171                 LatLon x2 = new LatLon(max.lat(),min.lon());
    172                 return new Point[] {
    173                         mv.getPoint(min), // south west
    174                         mv.getPoint(x1),
    175                         mv.getPoint(max),
    176                         mv.getPoint(x2) // north west
    177                         };
    178         }
    179         public String getDownloadUrl() {
    180                 return String.format("http://ftp2.cits.rncan.gc.ca/OSM/pub/%1$03d/%2$s/%1$03d%2$s%3$02d.zip",corda,cordb,cordc);
    181         }
    182         private ZipFile open_zip() throws IOException {
    183                 File download_path = new File(layer.plugin_self.getPluginDir() + File.separator);
    184                 download_path.mkdir();
    185                 CachedFile tile_zip = new CachedFile(getDownloadUrl()).setDestDir(download_path.toString());
    186                 return new ZipFile(tile_zip.getFile());
    187         }
    188         public void downloadSelf() {
    189                 if (zip_scanned) return;
    190                 ZipFile zipFile;
    191                 try {
    192                         zipFile = open_zip();
    193                 } catch (IOException e) {
    194                         e.printStackTrace();
    195                         return;
    196                 }
    197                 Enumeration<? extends ZipEntry> entries = zipFile.entries();
    198                 while (entries.hasMoreElements()) {
    199                         ZipEntry entry = entries.nextElement();
    200                         if (entry.getName().equals("Metadata.txt")) continue;
    201                         sub_tile_ids.add(entry.getName());
    202                         zip_scanned = true;
    203                         CanVecTile final_tile = new CanVecTile(entry.getName(),layer);
    204                         if (final_tile.isValid()) sub_tiles.add(final_tile);
    205                 }
    206         }
    207         public void load_raw_osm() {
    208                 ZipFile zipFile;
    209                 try {
    210                         zipFile = open_zip();
    211                         Enumeration<? extends ZipEntry> entries = zipFile.entries();
    212                         while (entries.hasMoreElements()) {
    213                                 ZipEntry entry = entries.nextElement();
    214                                 if (tileid.equals(entry.getName())) {
    215                                         debug("found myself!");
    216                                         InputStream rawtile = zipFile.getInputStream(entry);
    217                                         OsmImporter importer = new OsmImporter();
    218                                         debug("loading raw osm");
    219                                         OsmImporterData temp = importer.loadLayer(rawtile, null, entry.getName(), null);
    220                                         Main.worker.submit(temp.getPostLayerTask());
    221                                         Main.main.addLayer(temp.getLayer());
    222                                         temp.getLayer().data.setUploadDiscouraged(false);
    223                                 }
    224                         }
    225                 } catch (IOException e) {
    226                         e.printStackTrace();
    227                         return;
    228                 } catch (IllegalDataException e) {
    229                         e.printStackTrace();
    230                         return;
    231                 }
    232         }
    233         private void make_sub_tiles(int layer) {
    234                 ArrayList<String> buffer = new ArrayList<>();
    235                 Pattern p;
    236                 if (sub_tiles_made) return;
    237                 switch (layer) {
    238                 case 1:
    239                         p = Pattern.compile("\\d\\d\\d([A-Z]).*");
    240                         String last_cell = "";
    241                         for (int i = 0; i < index.size(); i++) {
    242                                 Matcher m = p.matcher(index.get(i));
    243                                 m.matches();
    244 
    245                                 String cell = m.group(1);
    246                                 if (cell.equals(last_cell)) {
    247                                         buffer.add(m.group(0));
    248                                 } else if (last_cell == "") {
    249                                         buffer.add(m.group(0));
    250                                 } else {
    251                                         sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
    252                                         buffer = new ArrayList<>();
    253                                         buffer.add(m.group(0));
    254                                 }
    255                                 last_cell = cell;
    256                         }
    257                         sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
    258                         break;
    259                 case 2:
    260                         p = Pattern.compile("\\d\\d\\d[A-Z](\\d\\d).*");
    261                         int last_cell2 = -1;
    262                         for (int i = 0; i < index.size(); i++) {
    263                                 Matcher m = p.matcher(index.get(i));
    264                                 m.matches();
    265 
    266                                 int cell = Integer.parseInt(m.group(1));
    267                                 if (cell == last_cell2) {
    268                                         buffer.add(m.group(0));
    269                                 } else if (last_cell2 == -1) {
    270                                         buffer.add(m.group(0));
    271                                 } else {
    272                                         sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
    273                                         buffer = new ArrayList<>();
    274                                         buffer.add(m.group(0));
    275                                 }
    276                                 last_cell2 = cell;
    277                         }
    278                         if (last_cell2 != -1) sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
    279                         break;
    280                 }
    281                 sub_tiles_made = true;
    282         }
    283         public void paint(Graphics2D g, MapView mv, Bounds bounds, int max_zoom) {
    284                 boolean show_sub_tiles = false;
    285                 if (!isVisible(bounds)) return;
    286                 if (depth == 4) {
    287                         layer.openable.add(this);
    288                 }
    289                 if ((depth == 3) && (bounds.getArea() < 0.5)) { // 022B01
    290                         if (zip_scanned) {
    291                                 show_sub_tiles = true;
    292                         } else if (can_download) {
    293                                 downloadSelf();
    294                                 show_sub_tiles = true;
    295                         } else {
    296                                 layer.downloadable.add(this);
    297                         }
    298                 } else if ((depth == 2) && (bounds.getArea() < 20)) { // its a layer2 tile
    299                         make_sub_tiles(2);
    300                         show_sub_tiles = true;
    301                 } else if ((depth == 1) && (bounds.getArea() < 40)) { // its a layer1 tile and zoom too small
    302                         // draw layer2 tiles for self
    303                         make_sub_tiles(1);
    304                         show_sub_tiles = true;
    305                 }
    306                 if (show_sub_tiles && (depth < max_zoom)) {
    307                         for (int i = 0; i < sub_tiles.size(); i++) {
    308                                 CanVecTile tile = sub_tiles.get(i);
    309                                 tile.paint(g,mv,bounds,max_zoom);
    310                         }
    311                 } else {
    312                         Point corners[] = getCorners(mv);
    313                         int xs[] = { corners[0].x, corners[1].x, corners[2].x, corners[3].x };
    314                         int ys[] = { corners[0].y, corners[1].y, corners[2].y, corners[3].y };
    315                         Polygon shape = new Polygon(xs,ys,4);
    316                         g.draw(shape);
    317                         g.drawString(getTileId(),corners[0].x,corners[0].y);
    318                 }
    319         }
     25    CanvecLayer layer;
     26    public boolean can_download = false;
     27    private ArrayList<String> sub_tile_ids = new ArrayList<>();
     28    private boolean zip_scanned = false;
     29   
     30    private ArrayList<CanVecTile> sub_tiles = new ArrayList<>();
     31    private boolean sub_tiles_made = false;
     32
     33    private ArrayList<String> index;
     34    private int depth;
     35   
     36    int corda,cordc;
     37    private boolean valid = false;
     38    String cordb,cordd;
     39    private Bounds bounds;
     40    public String tileid;
     41    public CanVecTile(String tileid,CanvecLayer layer) {
     42        String parta,partb,partc,partd;
     43        parta = tileid.substring(0,3);
     44        partb = tileid.substring(3, 4);
     45        partc = tileid.substring(4, 6);
     46        partd = tileid.substring(6);
     47        int a,c;
     48        a = Integer.parseInt(parta);
     49        c = Integer.parseInt(partc);
     50        real_init(a,partb,c,partd,layer,new ArrayList<String>());
     51    }
     52    public CanVecTile(int a,String b,int c,String d,CanvecLayer layer,ArrayList<String> index) {
     53        real_init(a,b,c,d,layer,index);
     54    }
     55    public void real_init(int a,String b,int c,String d,CanvecLayer layer, ArrayList<String> index) {
     56        this.index = index;
     57        this.layer = layer;
     58        corda = a;
     59        cordb = b;
     60        cordc = c;
     61        cordd = d;
     62        double zero_point_lat,zero_point_lon;
     63        double lat_span,lon_span;
     64        double lat2,lon2;
     65        if ((a >= 0) && (a <= 119)) { // main block of tiles
     66            int column = a / 10;
     67            int row = a % 10;
     68            if (row > 6) {
     69                // cant handle x7 x8 and x9 yet
     70                return;
     71            }
     72            zero_point_lat = 40 + 4 * row;
     73            zero_point_lon = -56 - 8 * column;
     74       
     75            // size of each grid
     76            if (row <= 6) {
     77                // each is 4x8 degrees, broken into a 4x4 grid
     78                lat_span = 4;
     79                lon_span = 8;
     80                depth = 1;
     81            } else {
     82                return;
     83            }
     84        } else { // last few tiles, very far north
     85            return;
     86        }
     87
     88        // a 4x4 grid of A thru P
     89        // map A-P to 1-16
     90        int grid2;
     91        if (b == "") grid2 = 0;
     92        else grid2 = b.charAt(0) - 64;
     93        int rows1[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
     94        int cols1[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
     95        lat2 = zero_point_lat + (lat_span/4)*rows1[grid2];
     96        lon2 = zero_point_lon + (lon_span/4)*cols1[grid2];
     97
     98        if (grid2 != 0) {
     99            lat_span = lat_span / 4;
     100            lon_span = lon_span / 4;
     101            depth = 2;
     102        }
     103
     104        int rows3[] = { 0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3 };
     105        lat2 = lat2 + (lat_span/4)*rows3[c];
     106        int cols3[] = { 0, 3,2,1,0, 0,1,2,3, 3,2,1,0, 0,1,2,3 };
     107        lon2 = lon2 + (lon_span/4)*cols3[c];
     108
     109        if (c != 0) {
     110            lat_span = lat_span / 4;
     111            lon_span = lon_span / 4;
     112            depth = 3;
     113        }
     114       
     115        if (cordd != "") {
     116            depth = 4;
     117            System.out.println("cordd: "+cordd);
     118            String foo[] = cordd.split("\\.");
     119            for (int i = 0; i < foo.length; i++) {
     120                int cell;
     121                System.out.println(foo[i]);
     122                if (foo[i] == "osm") break;
     123                if (foo[i] == "") continue;
     124                try {
     125                    cell = Integer.parseInt(foo[i]);
     126                } catch (NumberFormatException e) {
     127                    continue;
     128                }
     129                switch (cell) {
     130                case 0:
     131                    break;
     132                case 1:
     133                    lat2 = lat2 + lat_span/2;
     134                    break;
     135                case 2:
     136                    lat2 = lat2 + lat_span/2;
     137                    lon2 = lon2 + lon_span/2;
     138                    break;
     139                case 3:
     140                    lon2 = lon2 + lon_span/2;
     141                    break;
     142                }
     143                lat_span = lat_span/2;
     144                lon_span = lon_span/2;
     145            }
     146        }
     147
     148        bounds = new Bounds(lat2,lon2,lat2+lat_span,lon2+lon_span);
     149        if (cordb == "") this.tileid = String.format("%03d",corda);
     150        else if (cordc == 0) this.tileid = String.format("%03d%s",corda,cordb);
     151        else if (cordd == "") this.tileid = String.format("%03d%s%02d",corda,cordb,cordc);
     152        else this.tileid = String.format("%03d%s%02d%s",corda,cordb,cordc,cordd);
     153        valid = true;
     154        //debug(index.toString());
     155        //debug("creating tileid: "+this.tileid);
     156    }
     157    public boolean isValid() { return valid; }
     158    public String getTileId() {
     159        return this.tileid;
     160    }
     161    private void debug(String line) {
     162        System.out.println(depth + "_" + tileid + ": " + line);
     163    }
     164    public boolean isVisible(Bounds view) {
     165        return view.intersects(bounds);
     166    }
     167    public Point[] getCorners(MapView mv) {
     168        LatLon min = bounds.getMin();
     169        LatLon max = bounds.getMax();
     170        LatLon x1 = new LatLon(min.lat(),max.lon());
     171        LatLon x2 = new LatLon(max.lat(),min.lon());
     172        return new Point[] {
     173            mv.getPoint(min), // south west
     174            mv.getPoint(x1),
     175            mv.getPoint(max),
     176            mv.getPoint(x2) // north west
     177            };
     178    }
     179    public String getDownloadUrl() {
     180        return String.format("http://ftp2.cits.rncan.gc.ca/OSM/pub/%1$03d/%2$s/%1$03d%2$s%3$02d.zip",corda,cordb,cordc);
     181    }
     182    private ZipFile open_zip() throws IOException {
     183        File download_path = new File(layer.plugin_self.getPluginDir() + File.separator);
     184        download_path.mkdir();
     185        CachedFile tile_zip = new CachedFile(getDownloadUrl()).setDestDir(download_path.toString());
     186        return new ZipFile(tile_zip.getFile());
     187    }
     188    public void downloadSelf() {
     189        if (zip_scanned) return;
     190        ZipFile zipFile;
     191        try {
     192            zipFile = open_zip();
     193        } catch (IOException e) {
     194            e.printStackTrace();
     195            return;
     196        }
     197        Enumeration<? extends ZipEntry> entries = zipFile.entries();
     198        while (entries.hasMoreElements()) {
     199            ZipEntry entry = entries.nextElement();
     200            if (entry.getName().equals("Metadata.txt")) continue;
     201            sub_tile_ids.add(entry.getName());
     202            zip_scanned = true;
     203            CanVecTile final_tile = new CanVecTile(entry.getName(),layer);
     204            if (final_tile.isValid()) sub_tiles.add(final_tile);
     205        }
     206    }
     207    public void load_raw_osm() {
     208        ZipFile zipFile;
     209        try {
     210            zipFile = open_zip();
     211            Enumeration<? extends ZipEntry> entries = zipFile.entries();
     212            while (entries.hasMoreElements()) {
     213                ZipEntry entry = entries.nextElement();
     214                if (tileid.equals(entry.getName())) {
     215                    debug("found myself!");
     216                    InputStream rawtile = zipFile.getInputStream(entry);
     217                    OsmImporter importer = new OsmImporter();
     218                    debug("loading raw osm");
     219                    OsmImporterData temp = importer.loadLayer(rawtile, null, entry.getName(), null);
     220                    Main.worker.submit(temp.getPostLayerTask());
     221                    Main.main.addLayer(temp.getLayer());
     222                    temp.getLayer().data.setUploadDiscouraged(false);
     223                }
     224            }
     225        } catch (IOException e) {
     226            e.printStackTrace();
     227            return;
     228        } catch (IllegalDataException e) {
     229            e.printStackTrace();
     230            return;
     231        }
     232    }
     233    private void make_sub_tiles(int layer) {
     234        ArrayList<String> buffer = new ArrayList<>();
     235        Pattern p;
     236        if (sub_tiles_made) return;
     237        switch (layer) {
     238        case 1:
     239            p = Pattern.compile("\\d\\d\\d([A-Z]).*");
     240            String last_cell = "";
     241            for (int i = 0; i < index.size(); i++) {
     242                Matcher m = p.matcher(index.get(i));
     243                m.matches();
     244
     245                String cell = m.group(1);
     246                if (cell.equals(last_cell)) {
     247                    buffer.add(m.group(0));
     248                } else if (last_cell == "") {
     249                    buffer.add(m.group(0));
     250                } else {
     251                    sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
     252                    buffer = new ArrayList<>();
     253                    buffer.add(m.group(0));
     254                }
     255                last_cell = cell;
     256            }
     257            sub_tiles.add(new CanVecTile(corda,last_cell,0,"",this.layer,buffer));
     258            break;
     259        case 2:
     260            p = Pattern.compile("\\d\\d\\d[A-Z](\\d\\d).*");
     261            int last_cell2 = -1;
     262            for (int i = 0; i < index.size(); i++) {
     263                Matcher m = p.matcher(index.get(i));
     264                m.matches();
     265
     266                int cell = Integer.parseInt(m.group(1));
     267                if (cell == last_cell2) {
     268                    buffer.add(m.group(0));
     269                } else if (last_cell2 == -1) {
     270                    buffer.add(m.group(0));
     271                } else {
     272                    sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
     273                    buffer = new ArrayList<>();
     274                    buffer.add(m.group(0));
     275                }
     276                last_cell2 = cell;
     277            }
     278            if (last_cell2 != -1) sub_tiles.add(new CanVecTile(corda,cordb,last_cell2,"",this.layer,buffer));
     279            break;
     280        }
     281        sub_tiles_made = true;
     282    }
     283    public void paint(Graphics2D g, MapView mv, Bounds bounds, int max_zoom) {
     284        boolean show_sub_tiles = false;
     285        if (!isVisible(bounds)) return;
     286        if (depth == 4) {
     287            layer.openable.add(this);
     288        }
     289        if ((depth == 3) && (bounds.getArea() < 0.5)) { // 022B01
     290            if (zip_scanned) {
     291                show_sub_tiles = true;
     292            } else if (can_download) {
     293                downloadSelf();
     294                show_sub_tiles = true;
     295            } else {
     296                layer.downloadable.add(this);
     297            }
     298        } else if ((depth == 2) && (bounds.getArea() < 20)) { // its a layer2 tile
     299            make_sub_tiles(2);
     300            show_sub_tiles = true;
     301        } else if ((depth == 1) && (bounds.getArea() < 40)) { // its a layer1 tile and zoom too small
     302            // draw layer2 tiles for self
     303            make_sub_tiles(1);
     304            show_sub_tiles = true;
     305        }
     306        if (show_sub_tiles && (depth < max_zoom)) {
     307            for (int i = 0; i < sub_tiles.size(); i++) {
     308                CanVecTile tile = sub_tiles.get(i);
     309                tile.paint(g,mv,bounds,max_zoom);
     310            }
     311        } else {
     312            Point corners[] = getCorners(mv);
     313            int xs[] = { corners[0].x, corners[1].x, corners[2].x, corners[3].x };
     314            int ys[] = { corners[0].y, corners[1].y, corners[2].y, corners[3].y };
     315            Polygon shape = new Polygon(xs,ys,4);
     316            g.draw(shape);
     317            g.drawString(getTileId(),corners[0].x,corners[0].y);
     318        }
     319    }
    320320}
  • applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelper.java

    r29854 r30738  
    88public class CanvecHelper extends Plugin {
    99   
    10         public CanvecHelper(PluginInformation info) {
    11                 super(info);
    12                 Main.main.menu.imagerySubMenu.add(new CanvecHelperAction(this));
    13         }
    14        
     10    public CanvecHelper(PluginInformation info) {
     11        super(info);
     12        Main.main.menu.imagerySubMenu.add(new CanvecHelperAction(this));
     13    }
     14   
    1515    @Override
    16         public void mapFrameInitialized(MapFrame old, MapFrame new1) {
    17                 updateLayer();
    18         }
     16    public void mapFrameInitialized(MapFrame old, MapFrame new1) {
     17        updateLayer();
     18    }
    1919   
    20         private synchronized void updateLayer() {
    21         }
     20    private synchronized void updateLayer() {
     21    }
    2222}
  • applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelperAction.java

    r29854 r30738  
    55
    66public class CanvecHelperAction extends JosmAction {
    7         private CanvecHelper parent_temp;
    8         public CanvecHelperAction(CanvecHelper parent) {
    9                 super("CanVec Helper","layericon24",null,null,false);
    10                 parent_temp = parent;
    11         }
     7    private CanvecHelper parent_temp;
     8    public CanvecHelperAction(CanvecHelper parent) {
     9        super("CanVec Helper","layericon24",null,null,false);
     10        parent_temp = parent;
     11    }
    1212        @Override
    13         public void actionPerformed(java.awt.event.ActionEvent action) {
    14                 CanvecLayer layer;
    15                 layer = new CanvecLayer("canvec tile helper",parent_temp);
    16                 Main.main.addLayer(layer);
    17         }
     13    public void actionPerformed(java.awt.event.ActionEvent action) {
     14        CanvecLayer layer;
     15        layer = new CanvecLayer("canvec tile helper",parent_temp);
     16        Main.main.addLayer(layer);
     17    }
    1818}
  • applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecLayer.java

    r30737 r30738  
    11package org.openstreetmap.josm.plugins.canvec_helper;
     2
     3import static org.openstreetmap.josm.tools.I18n.tr;
    24
    35import java.awt.Color;
    46import java.awt.Component;
     7import java.awt.Graphics2D;
     8import java.awt.Toolkit;
    59import java.awt.event.ActionEvent;
    610import java.awt.event.MouseEvent;
    711import java.awt.event.MouseListener;
    8 import java.awt.Graphics2D;
    9 import java.awt.Toolkit;
    1012import java.io.BufferedReader;
     13import java.io.IOException;
    1114import java.io.InputStream;
    1215import java.io.InputStreamReader;
    13 import java.io.IOException;
    1416import java.util.ArrayList;
    1517import java.util.List;
    1618import java.util.regex.Matcher;
    1719import java.util.regex.Pattern;
     20
    1821import javax.swing.AbstractAction;
    1922import javax.swing.Action;
     
    2225import javax.swing.JMenu;
    2326import javax.swing.JMenuItem;
     27
     28import org.openstreetmap.josm.Main;
    2429import org.openstreetmap.josm.data.Bounds;
    2530import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
     31import org.openstreetmap.josm.gui.MapView;
    2632import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
    2733import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
    2834import org.openstreetmap.josm.gui.layer.Layer;
    29 import org.openstreetmap.josm.gui.MapView;
    3035import org.openstreetmap.josm.io.CachedFile;
    31 import static org.openstreetmap.josm.tools.I18n.tr;
    3236
    3337// most of the layout was copied from the openstreetbugs plugin to get things started
    3438public class CanvecLayer extends Layer implements MouseListener {
    35         private Icon layerIcon = null;
    36         private int max_zoom = 4;
    37         public CanvecHelper plugin_self;
    38         private ArrayList<CanVecTile> tiles = new ArrayList<>();
    39         public ArrayList<CanVecTile> downloadable = new ArrayList<>();
    40         public ArrayList<CanVecTile> openable = new ArrayList<>();
    41 
    42         public CanvecLayer(String name,CanvecHelper self){
    43                 super(name);
    44                 plugin_self = self;
    45                 this.setBackgroundLayer(true);
    46 /*              for (int i = 0; i < 119; i++) {
    47                         CanVecTile tile = new CanVecTile(i,"",0,"",plugin_self);
    48                         if (tile.isValid()) tiles.add(tile);
    49                 }*/
    50                 layerIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource("/images/layericon.png")));
    51                 try {
    52                         long start = System.currentTimeMillis();
    53                         Pattern p = Pattern.compile("(\\d\\d\\d)([A-Z]\\d\\d).*");
    54                         InputStream index = new CachedFile("http://ftp2.cits.rncan.gc.ca/OSM/pub/ZippedOsm.txt").getInputStream();
    55                         BufferedReader br = new BufferedReader(new InputStreamReader(index));
    56                         String line;
    57                         int last_cell = -1;
    58                         ArrayList<String> list = new ArrayList<>();
    59                         while ((line = br.readLine()) != null) {
    60                                 Matcher m = p.matcher(line);
    61                                 if (m.find()) {
    62                                         int cell = Integer.parseInt(m.group(1));
    63                                         if (cell == last_cell) {
    64                                                 list.add(m.group(0));
    65                                         } else if (last_cell != -1) {
    66                                                 CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
    67                                                 if (tile.isValid()) tiles.add(tile);
    68                                                 list = new ArrayList<>();
    69                                                 list.add(m.group(0));
    70                                         }
    71                                         last_cell = cell;
    72                                 } else if (line.contains("Metadata.txt")) {
    73                                 } else {
    74                                                 System.out.print("bad line '" + line + "'\n");
    75                                 }
    76                         }
    77                         br.close();
    78                         CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
    79                         if (tile.isValid()) tiles.add(tile);
    80 
    81                         long end = System.currentTimeMillis();
    82                         System.out.println((end-start)+"ms spent");
    83                 } catch (IOException e) {
    84                         System.out.println("exception getting index");
    85                         e.printStackTrace();
    86                 }
    87         }
    88         @Override
    89         public Action[] getMenuEntries() {
    90                 return new Action[]{
    91                         LayerListDialog.getInstance().createShowHideLayerAction(),
    92                         LayerListDialog.getInstance().createDeleteLayerAction(),
    93                         SeparatorLayerAction.INSTANCE,
    94                         new LayerListPopup.InfoAction(this),
    95                         new MaxZoomAction(this),
    96                         new DownloadCanvecAction(this),
    97                         new OpenOsmAction(this)};
    98         }
    99         public class MaxZoomAction extends AbstractAction implements LayerAction {
    100                 private CanvecLayer parent;
    101                 public MaxZoomAction(CanvecLayer parent) {
    102                         this.parent = parent;
    103                 }
    104                 @Override
    105                 public void actionPerformed(ActionEvent e) {}
    106                 @Override
    107                 public boolean supportLayers(List<Layer> layers) {
    108                         return false;
    109                 }
    110                 @Override
    111                 public Component createMenuComponent() {
    112                         JMenu max_zoom = new JMenu("max zoom");
    113                         max_zoom.add(new JMenuItem(new SetMaxZoom(parent,1)));
    114                         max_zoom.add(new JMenuItem(new SetMaxZoom(parent,2)));
    115                         max_zoom.add(new JMenuItem(new SetMaxZoom(parent,3)));
    116                         max_zoom.add(new JMenuItem(new SetMaxZoom(parent,4)));
    117                         return max_zoom;
    118                 }
    119         }
    120         private class AllowDownload extends AbstractAction {
    121                 CanVecTile tile;
    122                 public AllowDownload(CanVecTile tile) {
    123                         super(tile.tileid);
    124                         this.tile = tile;
    125                 }
    126                 @Override
    127                 public void actionPerformed(ActionEvent arg0) {
    128                         tile.can_download = true;
    129                 }
    130         }
    131         private class OpenOsmAction extends AbstractAction implements LayerAction {
    132                 private CanvecLayer layer;
    133                 public OpenOsmAction(CanvecLayer layer) {
    134                         this.layer = layer;
    135                 }
    136                 @Override
    137                 public void actionPerformed(ActionEvent e) {}
    138                 @Override
    139                 public Component createMenuComponent() {
    140                         JMenu OpenOsm = new JMenu("Open tile");
    141                         for (int i = 0; i < layer.openable.size(); i++) {
    142                                 OpenOsm.add(new JMenuItem(new DoOpenOsm(layer.openable.get(i))));
    143                         }
    144                         return OpenOsm;
    145                 }
    146                 @Override
    147                 public boolean supportLayers(List<Layer> layers) {
    148                         return false;
    149                 }
    150         }
    151         private class DoOpenOsm extends AbstractAction {
    152                 CanVecTile tile;
    153                 public DoOpenOsm(CanVecTile tile) {
    154                         super(tile.tileid);
    155                         this.tile = tile;
    156                 }
    157                 @Override
    158                 public void actionPerformed(ActionEvent e) {
    159                         tile.load_raw_osm();
    160                 }
    161         }
    162         private class DownloadCanvecAction extends AbstractAction implements LayerAction {
    163                 private CanvecLayer parent;
    164                 public DownloadCanvecAction(CanvecLayer parent) {
    165                         this.parent = parent;
    166                 }
    167                 @Override
    168                 public void actionPerformed(ActionEvent e) {}
    169                 @Override
    170                 public boolean supportLayers(List<Layer> layers) {
    171                         return false;
    172                 }
    173                 @Override
    174                 public Component createMenuComponent() {
    175                         JMenu downloadCanvec = new JMenu("Download zip's");
    176                         for (int i = 0; i < parent.downloadable.size(); i++) {
    177                                 downloadCanvec.add(new JMenuItem(new AllowDownload(parent.downloadable.get(i))));
    178                         }
    179                         return downloadCanvec;
    180                 }
    181         }
    182         public void setMaxZoom(int max_zoom) {
    183                 this.max_zoom = max_zoom;
    184         }
    185         @Override
    186         public Object getInfoComponent() {
    187                 return getToolTipText();
    188         }
    189         @Override
    190         public String getToolTipText() {
    191                 return tr("canvec tile helper");
    192         }
    193         @Override
    194         public void visitBoundingBox(BoundingXYVisitor v) {}
    195         @Override
    196         public boolean isMergable(Layer other) {
    197                 return false;
    198         }
    199         @Override
    200         public void mergeFrom(Layer from) {}
    201         @Override
    202         public Icon getIcon() { return layerIcon; }
    203         @Override
    204         public void paint(Graphics2D g, MapView mv, Bounds bounds) {
    205                 //long start = System.currentTimeMillis();
    206                 //System.out.println("painting the area covered by "+bounds.toString());
    207                 downloadable = new ArrayList<>();
    208                 openable = new ArrayList<>();
    209                 // loop over each canvec tile in the db and check bounds.intersects(Bounds)
    210                 g.setColor(Color.red);
    211                 for (int i = 0; i < tiles.size(); i++) {
    212                         CanVecTile tile = tiles.get(i);
    213                         tile.paint(g,mv,bounds,max_zoom);
    214                 }
    215                 //long end = System.currentTimeMillis();
    216                 //System.out.println((end-start)+"ms spent");
    217         }
    218         @Override
    219         public void mouseExited(MouseEvent e) {}
    220         @Override
    221         public void mouseEntered(MouseEvent e) {}
    222         @Override
    223         public void mouseReleased(MouseEvent e) {}
    224         @Override
    225         public void mousePressed(MouseEvent e) {}
    226         @Override
    227         public void mouseClicked(MouseEvent e) {
    228                 System.out.println("click!");
    229         }
     39    private Icon layerIcon = null;
     40    private int max_zoom = 4;
     41    public CanvecHelper plugin_self;
     42    private ArrayList<CanVecTile> tiles = new ArrayList<>();
     43    public ArrayList<CanVecTile> downloadable = new ArrayList<>();
     44    public ArrayList<CanVecTile> openable = new ArrayList<>();
     45
     46    public CanvecLayer(String name,CanvecHelper self){
     47        super(name);
     48        plugin_self = self;
     49        this.setBackgroundLayer(true);
     50/*        for (int i = 0; i < 119; i++) {
     51            CanVecTile tile = new CanVecTile(i,"",0,"",plugin_self);
     52            if (tile.isValid()) tiles.add(tile);
     53        }*/
     54        layerIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource("/images/layericon.png")));
     55        long start = System.currentTimeMillis();
     56        try (
     57            InputStream index = new CachedFile("http://ftp2.cits.rncan.gc.ca/OSM/pub/ZippedOsm.txt").getInputStream();
     58            BufferedReader br = new BufferedReader(new InputStreamReader(index));
     59        ) {
     60            Pattern p = Pattern.compile("(\\d\\d\\d)([A-Z]\\d\\d).*");
     61            String line;
     62            int last_cell = -1;
     63            ArrayList<String> list = new ArrayList<>();
     64            while ((line = br.readLine()) != null) {
     65                Matcher m = p.matcher(line);
     66                if (m.find()) {
     67                    int cell = Integer.parseInt(m.group(1));
     68                    if (cell == last_cell) {
     69                        list.add(m.group(0));
     70                    } else if (last_cell != -1) {
     71                        CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
     72                        if (tile.isValid()) tiles.add(tile);
     73                        list = new ArrayList<>();
     74                        list.add(m.group(0));
     75                    }
     76                    last_cell = cell;
     77                } else if (line.contains("Metadata.txt")) {
     78                } else {
     79                    System.out.print("bad line '" + line + "'\n");
     80                }
     81            }
     82            CanVecTile tile = new CanVecTile(last_cell,"",0,"",this,list);
     83            if (tile.isValid()) tiles.add(tile);
     84
     85            if (Main.isDebugEnabled()) {
     86                long end = System.currentTimeMillis();
     87                Main.debug((end-start)+"ms spent");
     88            }
     89        } catch (IOException e) {
     90            Main.error("exception getting index");
     91            Main.error(e);
     92        }
     93    }
     94    @Override
     95    public Action[] getMenuEntries() {
     96        return new Action[]{
     97            LayerListDialog.getInstance().createShowHideLayerAction(),
     98            LayerListDialog.getInstance().createDeleteLayerAction(),
     99            SeparatorLayerAction.INSTANCE,
     100            new LayerListPopup.InfoAction(this),
     101            new MaxZoomAction(this),
     102            new DownloadCanvecAction(this),
     103            new OpenOsmAction(this)};
     104    }
     105    public class MaxZoomAction extends AbstractAction implements LayerAction {
     106        private CanvecLayer parent;
     107        public MaxZoomAction(CanvecLayer parent) {
     108            this.parent = parent;
     109        }
     110                @Override
     111        public void actionPerformed(ActionEvent e) {}
     112                @Override
     113        public boolean supportLayers(List<Layer> layers) {
     114            return false;
     115        }
     116                @Override
     117        public Component createMenuComponent() {
     118            JMenu max_zoom = new JMenu("max zoom");
     119            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,1)));
     120            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,2)));
     121            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,3)));
     122            max_zoom.add(new JMenuItem(new SetMaxZoom(parent,4)));
     123            return max_zoom;
     124        }
     125    }
     126    private class AllowDownload extends AbstractAction {
     127        CanVecTile tile;
     128        public AllowDownload(CanVecTile tile) {
     129            super(tile.tileid);
     130            this.tile = tile;
     131        }
     132                @Override
     133        public void actionPerformed(ActionEvent arg0) {
     134            tile.can_download = true;
     135        }
     136    }
     137    private class OpenOsmAction extends AbstractAction implements LayerAction {
     138        private CanvecLayer layer;
     139        public OpenOsmAction(CanvecLayer layer) {
     140            this.layer = layer;
     141        }
     142                @Override
     143        public void actionPerformed(ActionEvent e) {}
     144                @Override
     145        public Component createMenuComponent() {
     146            JMenu OpenOsm = new JMenu("Open tile");
     147            for (int i = 0; i < layer.openable.size(); i++) {
     148                OpenOsm.add(new JMenuItem(new DoOpenOsm(layer.openable.get(i))));
     149            }
     150            return OpenOsm;
     151        }
     152                @Override
     153        public boolean supportLayers(List<Layer> layers) {
     154            return false;
     155        }
     156    }
     157    private class DoOpenOsm extends AbstractAction {
     158        CanVecTile tile;
     159        public DoOpenOsm(CanVecTile tile) {
     160            super(tile.tileid);
     161            this.tile = tile;
     162        }
     163                @Override
     164        public void actionPerformed(ActionEvent e) {
     165            tile.load_raw_osm();
     166        }
     167    }
     168    private class DownloadCanvecAction extends AbstractAction implements LayerAction {
     169        private CanvecLayer parent;
     170        public DownloadCanvecAction(CanvecLayer parent) {
     171            this.parent = parent;
     172        }
     173                @Override
     174        public void actionPerformed(ActionEvent e) {}
     175                @Override
     176        public boolean supportLayers(List<Layer> layers) {
     177            return false;
     178        }
     179                @Override
     180        public Component createMenuComponent() {
     181            JMenu downloadCanvec = new JMenu("Download zip's");
     182            for (int i = 0; i < parent.downloadable.size(); i++) {
     183                downloadCanvec.add(new JMenuItem(new AllowDownload(parent.downloadable.get(i))));
     184            }
     185            return downloadCanvec;
     186        }
     187    }
     188    public void setMaxZoom(int max_zoom) {
     189        this.max_zoom = max_zoom;
     190    }
     191        @Override
     192    public Object getInfoComponent() {
     193        return getToolTipText();
     194    }
     195        @Override
     196    public String getToolTipText() {
     197        return tr("canvec tile helper");
     198    }
     199        @Override
     200    public void visitBoundingBox(BoundingXYVisitor v) {}
     201        @Override
     202    public boolean isMergable(Layer other) {
     203        return false;
     204    }
     205        @Override
     206    public void mergeFrom(Layer from) {}
     207        @Override
     208    public Icon getIcon() { return layerIcon; }
     209        @Override
     210    public void paint(Graphics2D g, MapView mv, Bounds bounds) {
     211        //long start = System.currentTimeMillis();
     212        //System.out.println("painting the area covered by "+bounds.toString());
     213        downloadable = new ArrayList<>();
     214        openable = new ArrayList<>();
     215        // loop over each canvec tile in the db and check bounds.intersects(Bounds)
     216        g.setColor(Color.red);
     217        for (int i = 0; i < tiles.size(); i++) {
     218            CanVecTile tile = tiles.get(i);
     219            tile.paint(g,mv,bounds,max_zoom);
     220        }
     221        //long end = System.currentTimeMillis();
     222        //System.out.println((end-start)+"ms spent");
     223    }
     224        @Override
     225    public void mouseExited(MouseEvent e) {}
     226        @Override
     227    public void mouseEntered(MouseEvent e) {}
     228        @Override
     229    public void mouseReleased(MouseEvent e) {}
     230        @Override
     231    public void mousePressed(MouseEvent e) {}
     232        @Override
     233    public void mouseClicked(MouseEvent e) {
     234        System.out.println("click!");
     235    }
    230236}
  • applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/SetMaxZoom.java

    r29854 r30738  
    55
    66class SetMaxZoom extends AbstractAction {
    7         private CanvecLayer parent;
    8         private int level;
    9         public SetMaxZoom(CanvecLayer parent,int level) {
    10                 super(""+level);
    11                 this.level = level;
    12                 this.parent = parent;
    13         }
     7    private CanvecLayer parent;
     8    private int level;
     9    public SetMaxZoom(CanvecLayer parent,int level) {
     10        super(""+level);
     11        this.level = level;
     12        this.parent = parent;
     13    }
    1414        @Override
    15         public void actionPerformed(ActionEvent ev) {
    16                 parent.setMaxZoom(level);
    17         }
     15    public void actionPerformed(ActionEvent ev) {
     16        parent.setMaxZoom(level);
     17    }
    1818}
  • applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/DatabaseParser.java

    r23190 r30738  
    11package org.openstreetmap.josm.plugins.czechaddress.parser;
    22
    3 import org.openstreetmap.josm.plugins.czechaddress.addressdatabase.*;
    43import java.io.BufferedOutputStream;
    54import java.io.File;
     
    98import java.net.HttpURLConnection;
    109import java.net.URL;
     10
    1111import org.openstreetmap.josm.Main;
    1212import org.openstreetmap.josm.plugins.czechaddress.DatabaseLoadException;
     13import org.openstreetmap.josm.plugins.czechaddress.addressdatabase.Database;
    1314
    1415/**
     
    109110                        "Požadavek na server selhal, číslo chyby: " + String.valueOf( con.getResponseCode() ));
    110111
    111             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(getDatabasePath()));
    112 
    113             int total = 0, count;
    114             byte[] buffer = new byte[1024*512];
    115             while ((count = con.getInputStream().read(buffer)) >= 0) {
    116                 bos.write(buffer, 0, count);
    117                 total += count;
    118                 System.err.println("CzechAddress: MVČR database: " + String.valueOf(total/1024) + " kb downloaded.");
     112            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(getDatabasePath()))) {
     113                    int total = 0, count;
     114                    byte[] buffer = new byte[1024*512];
     115                    while ((count = con.getInputStream().read(buffer)) >= 0) {
     116                        bos.write(buffer, 0, count);
     117                        total += count;
     118                        Main.error("CzechAddress: MVČR database: " + String.valueOf(total/1024) + " kb downloaded.");
     119                    }
    119120            }
    120 
    121             bos.close();
    122121
    123122            // Look for a detailed error message from the server
  • applications/editors/josm/plugins/dataimport/src/org/openstreetmap/josm/plugins/dataimport/io/TangoGPS.java

    r30737 r30738  
    3030
    3131/**
    32  * @author dmuecke Data import for TangoGPS file format.
     32 * Data import for TangoGPS file format.
     33 * @author dmuecke
    3334 */
    3435public class TangoGPS extends FileImporter {
     
    4041    /**
    4142     * @author cbrill
    42      * This function imports data from file and adds trackpoints
    43      *         to a layer.
     43     * This function imports data from file and adds trackpoints to a layer.
    4444     * Read a log file from TangoGPS. These are simple text files in the
    4545     * form: <lat>,<lon>,<elevation>,<speed>,<course>,<hdop>,<datetime>
     
    5353        int failure = 0;
    5454
    55         BufferedReader rd = null;
    56         try {
     55        try (
    5756            InputStream source = new FileInputStream(file);
    58             rd = new BufferedReader(new InputStreamReader(source));
    59 
     57            BufferedReader rd = new BufferedReader(new InputStreamReader(source));
     58         ) {
    6059            String line;
    6160            while ((line = rd.readLine()) != null) {
     
    7271                        imported++;
    7372                    } catch (NumberFormatException e) {
    74                         e.printStackTrace();
     73                        Main.error(e);
    7574                    }
    7675                }
     
    9291            }
    9392            showInfobox(imported,failure);
    94         } finally {
    95             if (rd != null) {
    96                 rd.close();
    97             }
    9893        }
    9994    }
     
    106101        if (lineElements.length < 2)
    107102            return null;
    108         return new LatLon(parseCoord(lineElements[0]),
    109                 parseCoord(lineElements[1]));
     103        return new LatLon(parseCoord(lineElements[0]), parseCoord(lineElements[1]));
    110104    }
    111105
     
    118112        }
    119113    }
    120 
    121 
    122114}
  • applications/editors/josm/plugins/ext_tools/src/ext_tools/ToolsInformation.java

    r30737 r30738  
    88import java.util.ArrayList;
    99import java.util.List;
     10
     11import org.openstreetmap.josm.Main;
    1012
    1113public class ToolsInformation {
     
    2022
    2123    public void load() {
    22         try {
    23             BufferedReader rdr = new BufferedReader(new InputStreamReader(
    24                     new FileInputStream(filename), "UTF-8"));
     24        try (BufferedReader rdr = new BufferedReader(new InputStreamReader(
     25                    new FileInputStream(filename), "UTF-8"))) {
    2526            StringBuilder sb = new StringBuilder();
    2627            String line;
     
    3233                }
    3334            }
    34             rdr.close();
    3535        } catch (Exception e) {
    36             System.err.println("Ext_Tools warning: can not load file "+filename);
    37 //            e.printStackTrace();
     36            Main.warn("Ext_Tools warning: can not load file "+filename);
    3837        }
    3938    }
    4039
    4140    public void save() {
    42         try {
    43             OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(filename),
    44                     "UTF-8");
     41        try (OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")) {
    4542            for (ExtTool tool : tools)
    4643                w.write(tool.serialize());
    47             w.close();
    4844        } catch (Exception e) {
    49             System.err.println("Ext_Tools warning: can not save file "+filename);
    50 //            e.printStackTrace();
     45            Main.warn("Ext_Tools warning: can not save file "+filename);
    5146        }
    5247    }
  • applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Dg100Config.java

    r29854 r30738  
    1111import java.nio.ByteBuffer;
    1212import java.util.Properties;
     13
     14import org.openstreetmap.josm.Main;
    1315
    1416/**
     
    107109    }
    108110
    109     public String toString()
     111    @Override
     112        public String toString()
    110113    {
    111114        return
     
    459462        props.setProperty(propUnk3, "" + unk3);
    460463        props.setProperty(propUnk4, "" + unk4);
    461         OutputStream os = null;
    462         try
    463         {
    464             os = new FileOutputStream(fName);
     464
     465        try (OutputStream os = new FileOutputStream(fName)) {
    465466            props.store(os, "dg100 config");
    466         }
    467         catch (Exception ex)
    468         {
    469             ex.printStackTrace();
     467        } catch (Exception ex) {
     468            Main.error(ex);
    470469            throw ex;
    471470        }
    472         finally
    473         {
    474             if (os != null) {os.close();}
    475         }
    476     }
    477 
    478     public void readProps(String fName)
    479         throws Exception
    480     {
     471    }
     472
     473    public void readProps(String fName) throws Exception {
    481474        Properties props = new Properties();
    482         InputStream is = null;
    483         try
    484         {
    485             is = new FileInputStream(fName);
     475
     476        try (InputStream is = new FileInputStream(fName)) {
    486477            props.load(is);
    487         }
    488         catch (Exception ex)
    489         {
    490             ex.printStackTrace();
     478        } catch (Exception ex) {
     479            Main.error(ex);;
    491480            throw ex;
    492         }
    493         finally
    494         {
    495             if (is != null) {is.close();}
    496481        }
    497482        logFormat = Byte.parseByte(props.getProperty(propLogFormat, "2"));
  • applications/editors/josm/plugins/gpxfilter/src/gpxfilter/GpxGrabber.java

    r29222 r30738  
    2323    private final double lat2;
    2424    private final double lon2;
    25    
     25
    2626    private int page;
    2727
     
    3131        this.lat2 = downloadArea.getMax().lat();
    3232        this.lon2 = downloadArea.getMax().lon();
    33        
     33
    3434        page = 0;
    3535    }
     
    4242     */
    4343    public GpxData parseRawGps() throws IOException, SAXException,OsmTransferException {
    44         try {
    45             String url = "trackpoints?bbox="+lon1+","+lat1+","+lon2+","+lat2+"&page="+page;
    46 
    47             InputStream in = getInputStream(url, NullProgressMonitor.INSTANCE);
     44        String url = "trackpoints?bbox="+lon1+","+lat1+","+lon2+","+lat2+"&page="+page;
     45        try (InputStream in = getInputStream(url, NullProgressMonitor.INSTANCE)) {
    4846            GpxReader reader = new GpxReader(in);
    4947            reader.parse(false);
    5048            GpxData result = reader.getGpxData();
    51             in.close();
    5249            result.fromServer = true;
    5350            page++;
     
    7067                return null;
    7168            throw e;
    72         }    }
     69        }
     70    }
    7371
    7472    @Override
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetPlugin.java

    r30737 r30738  
    11package iodb;
    22
     3import static org.openstreetmap.josm.tools.I18n.marktr;
     4
    35import java.awt.event.KeyEvent;
    4 import java.util.*;
     6import java.util.Collection;
     7import java.util.LinkedList;
     8
    59import javax.swing.JMenu;
     10
    611import org.openstreetmap.josm.Main;
    712import org.openstreetmap.josm.data.Version;
     13import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
    814import org.openstreetmap.josm.plugins.Plugin;
    915import org.openstreetmap.josm.plugins.PluginInformation;
    10 import static org.openstreetmap.josm.tools.I18n.marktr;
    1116
    1217/**
    1318 * A plugin to request and store imagery offsets in the centralized database.
    14  * 
     19 *
    1520 * @author Zverik
    1621 * @license WTFPL
     
    1924    private GetImageryOffsetAction getAction;
    2025    private StoreImageryOffsetAction storeAction;
    21    
     26
    2227    /**
    2328     * Add both actions to their own menu. This creates
     
    2833    public ImageryOffsetPlugin( PluginInformation info ) {
    2934        super(info);
    30        
     35
    3136        getAction = new GetImageryOffsetAction();
    3237        storeAction = new StoreImageryOffsetAction();
    33        
     38
    3439        // before 5803 imagery menu was constantly regenerated, erasing extra items
    3540        // before 5729 it was regenerated only when the imagery list was modified (also bad)
     
    4348        // an ugly hack to add this plugin to the toolbar
    4449        if( Main.pref.getBoolean("iodb.modify.toolbar", true) ) {
    45             Collection<String> toolbar = new LinkedList<>(Main.toolbar.getToolString());
     50            Collection<String> toolbar = new LinkedList<>(ToolbarPreferences.getToolString());
    4651            if( !toolbar.contains("getoffset") ) {
    4752                toolbar.add("getoffset");
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialog.java

    r30737 r30738  
    11package iodb;
    22
    3 import java.awt.*;
     3import static org.openstreetmap.josm.tools.I18n.tr;
     4
     5import java.awt.BasicStroke;
     6import java.awt.Color;
     7import java.awt.Component;
     8import java.awt.FlowLayout;
     9import java.awt.Graphics2D;
     10import java.awt.GridLayout;
     11import java.awt.Point;
     12import java.awt.RenderingHints;
    413import java.awt.event.ActionEvent;
    514import java.awt.event.ActionListener;
     
    817import java.net.HttpURLConnection;
    918import java.net.URL;
    10 import java.util.*;
     19import java.util.ArrayList;
     20import java.util.Date;
    1121import java.util.List;
    12 import javax.swing.*;
     22
     23import javax.swing.AbstractAction;
     24import javax.swing.Box;
     25import javax.swing.BoxLayout;
     26import javax.swing.JButton;
     27import javax.swing.JCheckBox;
     28import javax.swing.JComponent;
     29import javax.swing.JDialog;
     30import javax.swing.JOptionPane;
     31import javax.swing.JPanel;
     32import javax.swing.JPopupMenu;
     33import javax.swing.KeyStroke;
    1334import javax.swing.border.CompoundBorder;
    1435import javax.swing.border.EmptyBorder;
     36
    1537import org.openstreetmap.josm.Main;
    1638import org.openstreetmap.josm.data.Bounds;
     
    1941import org.openstreetmap.josm.gui.layer.ImageryLayer;
    2042import org.openstreetmap.josm.gui.layer.MapViewPaintable;
    21 import org.openstreetmap.josm.tools.*;
    22 import static org.openstreetmap.josm.tools.I18n.tr;
     43import org.openstreetmap.josm.tools.ImageProvider;
     44import org.openstreetmap.josm.tools.LanguageInfo;
     45import org.openstreetmap.josm.tools.OpenBrowser;
     46import org.openstreetmap.josm.tools.Utils;
    2347
    2448/**
    2549 * The dialog which presents a choice between imagery align options.
    26  * 
     50 *
    2751 * @author Zverik
    2852 * @license WTFPL
     
    3155    protected static final String PREF_CALIBRATION = "iodb.show.calibration";
    3256    protected static final String PREF_DEPRECATED = "iodb.show.deprecated";
    33     private static final int MAX_OFFSETS = Main.main.pref.getInteger("iodb.max.offsets", 4);
     57    private static final int MAX_OFFSETS = Main.pref.getInteger("iodb.max.offsets", 4);
    3458
    3559    /**
     
    4569
    4670    /**
    47      * Initialize the dialog and install listeners. 
     71     * Initialize the dialog and install listeners.
    4872     * @param offsets The list of offset to choose from.
    4973     */
     
    6084                JComponent.WHEN_IN_FOCUSED_WINDOW);
    6185    }
    62    
     86
    6387    /**
    6488     * Creates the GUI.
     
    6993        calibrationBox.setSelected(Main.pref.getBoolean(PREF_CALIBRATION, true));
    7094        calibrationBox.addActionListener(new ActionListener() {
    71             public void actionPerformed( ActionEvent e ) {
     95            @Override
     96                        public void actionPerformed( ActionEvent e ) {
    7297                Main.pref.put(PREF_CALIBRATION, calibrationBox.isSelected());
    7398                updateButtonPanel();
     
    77102        deprecatedBox.setSelected(Main.pref.getBoolean(PREF_DEPRECATED, false));
    78103        deprecatedBox.addActionListener(new ActionListener() {
    79             public void actionPerformed( ActionEvent e ) {
     104            @Override
     105                        public void actionPerformed( ActionEvent e ) {
    80106                Main.pref.put(PREF_DEPRECATED, deprecatedBox.isSelected());
    81107                updateButtonPanel();
     
    154180     * It does nothing, only passes the event to all displayed offset buttons.
    155181     */
    156     public void zoomChanged() {
     182    @Override
     183        public void zoomChanged() {
    157184        for( Component c : buttonPanel.getComponents() ) {
    158185            if( c instanceof OffsetDialogButton ) {
     
    166193     * value, but looks nice.
    167194     */
    168     public void paint( Graphics2D g, MapView mv, Bounds bbox ) {
     195    @Override
     196        public void paint( Graphics2D g, MapView mv, Bounds bbox ) {
    169197        if( offsets == null )
    170198            return;
     
    181209        }
    182210    }
    183    
     211
    184212    /**
    185213     * Display the dialog and get the return value is case of a modal frame.
     
    208236     * @see #applyOffset()
    209237     */
    210     public void actionPerformed( ActionEvent e ) {
     238    @Override
     239        public void actionPerformed( ActionEvent e ) {
    211240        if( e.getSource() instanceof OffsetDialogButton ) {
    212241            selectedOffset = ((OffsetDialogButton)e.getSource()).getOffset();
     
    283312         * Remove the deprecated offset from the offsets list. Then rebuild the button panel.
    284313         */
    285         public void queryPassed() {
     314        @Override
     315                public void queryPassed() {
    286316            offset.setDeprecated(new Date(), JosmUserIdentityManager.getInstance().getUserName(), "");
    287317            updateButtonPanel();
     
    299329        }
    300330
    301         public void actionPerformed( ActionEvent e ) {
     331        @Override
     332                public void actionPerformed( ActionEvent e ) {
    302333            String base = Main.pref.get("url.openstreetmap-wiki", "http://wiki.openstreetmap.org/wiki/");
    303334            String lang = LanguageInfo.getWikiLanguagePrefix();
  • applications/editors/josm/plugins/imagery_offset_db/src/iodb/StoreImageryOffsetAction.java

    r30737 r30738  
    117117                query.append(key).append('=').append(URLEncoder.encode(params.get(key), "UTF8"));
    118118            }
    119             Main.main.worker.submit(new SimpleOffsetQueryTask(query.toString(), tr("Uploading a new offset...")));
     119            Main.worker.submit(new SimpleOffsetQueryTask(query.toString(), tr("Uploading a new offset...")));
    120120        } catch( UnsupportedEncodingException ex ) {
    121121            // WTF
  • applications/editors/josm/plugins/imagerycache/src/org/openstreetmap/josm/plugins/imagerycache/OsmDBTilesLoader.java

    r29769 r30738  
    1111import java.util.Map;
    1212import java.util.Random;
     13
    1314import org.openstreetmap.gui.jmapviewer.JobDispatcher;
    1415import org.openstreetmap.gui.jmapviewer.OsmTileLoader;
     
    2021import org.openstreetmap.gui.jmapviewer.interfaces.TileSource;
    2122import org.openstreetmap.gui.jmapviewer.interfaces.TileSource.TileUpdate;
     23import org.openstreetmap.josm.Main;
    2224import org.openstreetmap.josm.data.preferences.BooleanProperty;
    2325
    2426/**
    25  * 
     27 *
    2628 * @author Alexei Kasatkin, based on OsmFileCacheTileLoader by @author Jan Peter Stotz, @author Stefan Zeller
    2729 */
    2830class OsmDBTilesLoader extends OsmTileLoader implements CachedTileLoader {
    29    
    30    
     31
     32
    3133    public static final long FILE_AGE_ONE_DAY = 1000 * 60 * 60 * 24;
    3234    public static final long FILE_AGE_ONE_WEEK = FILE_AGE_ONE_DAY * 7;
    33    
     35
    3436    public static final boolean debug = new BooleanProperty("imagerycache.debug", false).get();
    35            
     37
    3638    TileDAOMapDB dao;
    37    
     39
    3840    protected long maxCacheFileAge = FILE_AGE_ONE_WEEK;
    3941    protected long recheckAfter = FILE_AGE_ONE_DAY;
    4042
    41    
     43
    4244    public OsmDBTilesLoader(TileLoaderListener smap, File cacheFolder) {
    4345        super(smap);
     
    4547        dao.setCacheFolder(cacheFolder);
    4648    }
    47    
     49
    4850    @Override
    4951    public TileJob createTileLoaderJob(final Tile tile) {
     
    6062        dao.cleanStorage(source.getName());
    6163    }
    62    
     64
    6365    protected class DatabaseLoadJob implements TileJob {
    6466
    6567        private final Tile tile;
    6668        File tileCacheDir;
    67        
     69
    6870        /**
    69          * Stores the tile loaded from database, null if nothing found. 
     71         * Stores the tile loaded from database, null if nothing found.
    7072         */
    7173        DBTile dbTile = null;
    7274        long fileAge = 0;
    73        
     75
    7476        long id;
    7577        String sourceName;
    76        
     78
    7779        public DatabaseLoadJob(Tile tile) {
    7880            this.tile = tile;
     
    112114
    113115        /**
    114          * Loads tile from database. 
     116         * Loads tile from database.
    115117         * There can be dbTile != null but the tile is outdated and reload is still needed
    116118         * @return true if no loading from server is needed.
     
    120122            try {
    121123                dbTile = dao.getById(sourceName, id);
    122                
     124
    123125                if (dbTile == null) return false;
    124                
    125                 loadMetadata(); 
     126
     127                loadMetadata();
    126128                if (debug) System.out.println(id+": found in cache, metadata ="+dbTile.metaData);
    127129
     
    149151                }
    150152            } catch (Exception e) {
    151                 System.out.println("Error: Can not load tile from database: "+sourceName+":"+id);
    152                 e.printStackTrace(System.out);
     153                Main.error("Error: Can not load tile from database: "+sourceName+":"+id);
     154                Main.error(e);
    153155                try {
    154156                    if (bin != null) {
     
    161163                return false; // tile is not because of some error (corrupted database, etc.)
    162164            } catch (Error e) { // this is bad, bat MapDB throws it
    163                 System.out.println("Serious database error: Can not load tile from database: "+sourceName+":"+id);
    164                 e.printStackTrace(System.out);
    165                 dbTile = null;  fileAge = 0;  return false;                                           
     165                Main.error("Serious database error: Can not load tile from database: "+sourceName+":"+id);
     166                Main.error(e);
     167                dbTile = null;  fileAge = 0;  return false;
    166168            }
    167169        }
     
    170172            return System.currentTimeMillis() - maxCacheFileAge + recheckAfter;
    171173        }
    172                
     174
    173175        private void loadOrUpdateTileFromServer() {
    174            
     176
    175177            try {
    176178                URLConnection urlConn = loadTileFromOsm(tile);
     
    195197                    dbTile = new DBTile();
    196198                }
    197                
     199
    198200                if (tileUpdate == TileSource.TileUpdate.ETag || tileUpdate == TileSource.TileUpdate.IfNoneMatch) {
    199201                    String fileETag = tile.getValue("etag");
     
    224226                loadTileMetadata(tile, urlConn);
    225227                dbTile.metaData = tile.getMetadata();
    226                
     228
    227229                if ("no-tile".equals(tile.getValue("tile-info")))
    228230                {
     
    248250                    }
    249251                }
    250                
     252
    251253            } catch (Exception e) {
    252254                tile.setError(e.getMessage());
     
    261263            }
    262264        }
    263        
    264        
     265
     266
    265267        protected byte[] loadTileInBuffer(URLConnection urlConn) throws IOException {
    266268            InputStream input = urlConn.getInputStream();
     
    292294         * </ul>
    293295         *
    294          * @param fileAge time of the 
     296         * @param fileAge time of the
    295297         * @return <code>true</code> if the tile on the server is newer than the
    296298         *         file
  • applications/editors/josm/plugins/mapdust/src/org/openstreetmap/josm/plugins/mapdust/util/http/HttpConnector.java

    r25591 r30738  
    3838import java.net.URLEncoder;
    3939import java.util.Map;
     40
    4041import org.openstreetmap.josm.plugins.mapdust.util.retry.RetryAgent;
    4142import org.openstreetmap.josm.plugins.mapdust.util.retry.RetrySetup;
     
    160161                /* 3: write content */
    161162                if (sbEncodeParameters.length() > 0) {
    162                     OutputStreamWriter out =
    163                             new OutputStreamWriter(connection.getOutputStream());
    164 
    165                     out.write(sbEncodeParameters.toString());
    166                     out.close();
     163                    try (OutputStreamWriter out =
     164                            new OutputStreamWriter(connection.getOutputStream())) {
     165                        out.write(sbEncodeParameters.toString());
     166                    }
    167167                }
    168168
  • applications/editors/josm/plugins/native-password-manager/src/org/netbeans/modules/keyring/kde/KWalletProvider.java

    r26335 r30738  
    4949import java.util.logging.Level;
    5050import java.util.logging.Logger;
     51
    5152import org.netbeans.spi.keyring.KeyringProvider;
    5253
     
    6970        }
    7071        CommandResult result = runCommand("isEnabled");
    71         if(new String(result.retVal).equals("true")) {       
     72        if(new String(result.retVal).equals("true")) {
    7273            return updateHandler();
    73         }                   
     74        }
    7475        return false;
    7576    };
     
    121122        }
    122123        handler = new String(handler).equals("")? "0".toCharArray() : handler;
    123         CommandResult result = runCommand("isOpen",handler);         
     124        CommandResult result = runCommand("isOpen",handler);
    124125        if(new String(result.retVal).equals("true")){
    125126            return true;
    126127        }
    127128        char[] localWallet = defaultLocalWallet;
    128         result = runCommand("localWallet");                     
    129         if(result.exitCode == 0) {                   
     129        result = runCommand("localWallet");
     130        if(result.exitCode == 0) {
    130131            localWallet = result.retVal;
    131132        }
    132            
    133         if(new String(localWallet).contains(".service")) {           
     133
     134        if(new String(localWallet).contains(".service")) {
    134135            //Temporary workaround for the bug in kdelibs/kdeui/util/kwallet.cpp
    135136            //The bug was fixed http://svn.reviewboard.kde.org/r/5885/diff/
     
    138139        }
    139140        result = runCommand("open", localWallet , "0".toCharArray(), getApplicationName(true));
    140         if(result.exitCode == 2) { 
     141        if(result.exitCode == 2) {
    141142            warning("time out happened while accessing KWallet");
    142143            //don't try to open KWallet anymore until bug https://bugs.kde.org/show_bug.cgi?id=259229 is fixed
    143144            timeoutHappened = true;
    144145            return false;
    145         }     
     146        }
    146147        if(result.exitCode != 0 || new String(result.retVal).equals("-1")) {
    147148            warning("failed to access KWallet");
    148149            return false;
    149         }         
     150        }
    150151        handler = result.retVal;
    151152        return true;
    152153    }
    153          
    154    
     154
     155
    155156
    156157    private CommandResult runCommand(String command,char[]... commandArgs) {
     
    174175            }
    175176            Process pr = rt.exec(argv);
    176            
    177             BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    178 
    179177            String line;
    180             while((line = input.readLine()) != null) {
    181                 if (!retVal.equals("")){
    182                     retVal = retVal.concat("\n");
     178
     179            try (BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
     180                while((line = input.readLine()) != null) {
     181                    if (!retVal.equals("")){
     182                        retVal = retVal.concat("\n");
     183                    }
     184                    retVal = retVal.concat(line);
    183185                }
    184                 retVal = retVal.concat(line);
    185             }           
    186             input.close();
    187             input = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    188 
    189             while((line = input.readLine()) != null) {
    190                 if (!errVal.equals("")){
    191                     errVal = errVal.concat("\n");
     186            }
     187
     188            try (BufferedReader input = new BufferedReader(new InputStreamReader(pr.getErrorStream()))) {
     189                while((line = input.readLine()) != null) {
     190                    if (!errVal.equals("")){
     191                        errVal = errVal.concat("\n");
     192                    }
     193                    errVal = errVal.concat(line);
    192194                }
    193                 errVal = errVal.concat(line);
    194             }
    195             input.close();
     195            }
    196196
    197197            exitCode = pr.waitFor();
     
    199199                logger.log(Level.FINE, "application exit with code {0} for commandString: {1}; errVal: {2}",
    200200                            new Object[]{exitCode, Arrays.toString(argv), errVal});
    201             }       
     201            }
    202202        } catch (InterruptedException ex) {
    203203            logger.log(Level.FINE,
     
    210210        }
    211211        return new CommandResult(exitCode, retVal.trim().toCharArray(), errVal.trim());
    212     }   
     212    }
    213213
    214214    private char[] getApplicationName(){
     
    222222    private void warning(String descr) {
    223223        logger.log(Level.WARNING, "Something went wrong: {0}", descr);
    224     }     
    225  
     224    }
     225
    226226    private class CommandResult {
    227227        private int exitCode;
    228228        private char[] retVal;
    229         private String errVal;
    230229
    231230        public CommandResult(int exitCode, char[] retVal, String errVal) {
    232231            this.exitCode = exitCode;
    233232            this.retVal = retVal;
    234             this.errVal = errVal;
    235         }                       
     233        }
    236234    }
    237235
  • applications/editors/josm/plugins/opendata/includes/org/apache/poi/hssf/record/formula/function/FunctionMetadataReader.java

    r30737 r30738  
    2222import java.io.InputStream;
    2323import java.io.InputStreamReader;
    24 import java.io.UnsupportedEncodingException;
    2524import java.util.Arrays;
    2625import java.util.HashSet;
     
    3231/**
    3332 * Converts the text meta-data file into a <tt>FunctionMetadataRegistry</tt>
    34  * 
     33 *
    3534 * @author Josh Micich
    3635 */
     
    3837
    3938        private static final String METADATA_FILE_NAME = "functionMetadata.txt";
    40        
     39
    4140        /** plain ASCII text metadata file uses three dots for ellipsis */
    4241        private static final String ELLIPSIS = "...";
     
    5958                }
    6059
    61                 BufferedReader br;
    62                 try {
    63                         br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
    64                 } catch(UnsupportedEncodingException e) {
    65                         throw new RuntimeException(e);
    66                 }
    6760                FunctionDataBuilder fdb = new FunctionDataBuilder(400);
    6861
    69                 try {
     62                try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
    7063                        while (true) {
    7164                                String line = br.readLine();
     
    8275                                processLine(fdb, line);
    8376                        }
    84                         br.close();
    8577                } catch (IOException e) {
    8678                        throw new RuntimeException(e);
     
    10799                validateFunctionName(functionName);
    108100                // TODO - make POI use isVolatile
    109                 fdb.add(functionIndex, functionName, minParams, maxParams, 
     101                fdb.add(functionIndex, functionName, minParams, maxParams,
    110102                                returnClassCode, parameterClassCodes, hasNote);
    111103        }
    112        
     104
    113105
    114106        private static byte parseReturnTypeCode(String code) {
     
    164156
    165157        /**
    166          * Makes sure that footnote digits from the original OOO document have not been accidentally 
     158         * Makes sure that footnote digits from the original OOO document have not been accidentally
    167159         * left behind
    168160         */
     
    182174                        return;
    183175                }
    184                 throw new RuntimeException("Invalid function name '" + functionName 
     176                throw new RuntimeException("Invalid function name '" + functionName
    185177                                + "' (is footnote number incorrectly appended)");
    186178        }
  • applications/editors/josm/plugins/opendata/modules/fr.datagouvfr/src/org/openstreetmap/josm/plugins/opendata/modules/fr/datagouvfr/datasets/hydrologie/EauxDeSurfaceHandler.java

    r30731 r30738  
    1414import java.util.regex.Pattern;
    1515
     16import org.openstreetmap.josm.Main;
    1617import org.openstreetmap.josm.data.osm.DataSet;
    1718import org.openstreetmap.josm.plugins.opendata.core.io.archive.DefaultArchiveHandler;
     
    2324    private static final String ZIP_PATTERN = "FR(.*)_SW";
    2425    private static final String SHP_PATTERN = "FR_(.*)_SWB_.W_20......";
    25    
     26
    2627    private static final class WaterAgency {
    2728        public final String code;
     
    3435        }
    3536    }
    36    
     37
    3738    private static final WaterAgency[] waterAgencies = new WaterAgency[]{
    3839        new WaterAgency("A",  "Escaut Somme", "Escaut-Somme-30381967"),
     
    4950        new WaterAgency("L",  "La Réunion", "Réunion-30381991"),
    5051    };
    51    
     52
    5253    public EauxDeSurfaceHandler() {
    5354        setName("Eaux de surface");
    5455        setArchiveHandler(new InternalZipHandler());
    5556    }
    56    
     57
    5758    @Override
    5859    public boolean acceptsFilename(String filename) {
     
    6364        return result;
    6465    }
    65    
     66
    6667    @Override
    6768    public boolean acceptsUrl(String url) {
     
    9192        // TODO Auto-generated method stub
    9293    }
    93    
     94
    9495    @Override
    9596    public List<Pair<String, URL>> getDataURLs() {
     
    106107
    107108    private Pair<String, URL> getDownloadURL(WaterAgency a) throws MalformedURLException {
    108         return new Pair<>("SurfaceWater_"+a.name, new URL("http://www.rapportage.eaufrance.fr/sites/default/files/SIG/FR"+a.code+"_SW.zip"));
     109        return new Pair<>("SurfaceWater_"+a.name,
     110                new URL("http://www.rapportage.eaufrance.fr/sites/default/files/SIG/FR"+a.code+"_SW.zip"));
    109111    }
    110    
     112
    111113    private class InternalZipHandler extends DefaultArchiveHandler {
    112114        @Override
    113115        public void notifyTempFileWritten(File file) {
    114             if (file.getName().matches(SHP_PATTERN.replace("(.*)", "F")+"\\.prj")) { // Adour-Garonne .prj files cannot be parsed because they do not contain quotes... 
    115                 try {
    116                     BufferedReader reader = new BufferedReader(new FileReader(file));
     116            // Adour-Garonne .prj files cannot be parsed because they do not contain quotes...
     117            if (file.getName().matches(SHP_PATTERN.replace("(.*)", "F")+"\\.prj")) {
     118                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
    117119                    String line = reader.readLine();
    118                     reader.close();
    119120                    if (!line.contains("\"")) {
    120121                        for (String term : new String[]{"GCS_ETRS_1989", "D_ETRS_1989", "GRS_1980", "Greenwich", "Degree"}) {
    121122                            line = line.replace(term, "\""+term+"\"");
    122123                        }
    123                         BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    124                         writer.write(line);
    125                         writer.close();
     124                        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
     125                            writer.write(line);
     126                        }
    126127                    }
    127128                } catch (Exception e) {
    128                     e.printStackTrace();
     129                    Main.error(e);
    129130                }
    130131            }
  • applications/editors/josm/plugins/opendata/src/org/geotools/data/shapefile/files/TabFiles.java

    r30731 r30738  
    717717     *                 if a problem occurred opening the stream.
    718718     */
     719    @SuppressWarnings("resource")
    719720    @Override
    720721    public OutputStream getOutputStream(ShpFileType type,
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/NeptuneReader.java

    r30723 r30738  
    44import java.io.File;
    55import java.io.FileInputStream;
    6 import java.io.FileNotFoundException;
    76import java.io.IOException;
    87import java.io.InputStream;
     
    5453/**
    5554 * NEPTUNE -> OSM converter
    56  * See http://www.chouette.mobi/IMG/pdf/NF__F_-Neptune-maj.pdf 
     55 * See http://www.chouette.mobi/IMG/pdf/NF__F_-Neptune-maj.pdf
    5756 */
    5857public class NeptuneReader extends AbstractReader implements FrenchConstants {
     
    8180        schemas.add(NeptuneReader.class.getResource(NEPTUNE_XSD));
    8281    }
    83    
     82
    8483    private ChouettePTNetworkType root;
    85    
     84
    8685    private final Map<String, OsmPrimitive> tridentObjects = new HashMap<>();
    87    
     86
    8887    public static final boolean acceptsXmlNeptuneFile(File file) {
    8988        return acceptsXmlNeptuneFile(file, null);
     
    9190
    9291    public static final boolean acceptsXmlNeptuneFile(File file, URL schemaURL) {
    93        
     92
    9493        if (schemaURL == null) {
    9594            schemaURL = schemas.get(0);
    9695        }
    97        
    98         try {
    99             FileInputStream in = new FileInputStream(file);
     96
     97        try (FileInputStream in = new FileInputStream(file)) {
    10098            Source xmlFile = new StreamSource(in);
    10199            try {
     
    112110                Main.error(xmlFile.getSystemId() + " is NOT valid");
    113111                Main.error("Reason: " + e.getLocalizedMessage());
    114             } finally {
    115                 try {
    116                     in.close();
    117                 } catch (IOException e) {
    118                     // Ignore exception
    119                 }
    120112            }
    121         } catch (FileNotFoundException e) {
     113        } catch (IOException e) {
    122114            Main.error(e.getMessage());
    123115        }
    124        
     116
    125117        return false;
    126118    }
    127    
     119
    128120    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance) throws JAXBException {
    129121        return new NeptuneReader().parse(in, instance);
     
    138130        return doc.getValue();
    139131    }
    140    
     132
    141133    private final void linkTridentObjectToOsmPrimitive(TridentObjectType object, OsmPrimitive p) {
    142134        p.put("ref:neptune", object.getObjectId());
     
    151143        return n;
    152144    }
    153    
     145
    154146    private Node createPlatform(StopPointType stop) {
    155147        Node n = createNode(createLatLon(stop));
     
    181173        return r;
    182174    }
    183    
     175
    184176    protected Relation createNetwork(PTNetworkType network) {
    185177        Relation r = createRelation(OSM_NETWORK);
     
    188180        return r;
    189181    }
    190    
     182
    191183    protected Relation createRouteMaster(LineType line) {
    192184        Relation r = createPtRelation(OSM_ROUTE_MASTER, line);
     
    219211        return r;
    220212    }
    221    
     213
    222214    protected Relation createStopArea(StopAreaType sa) {
    223215        Relation r = createPtRelation(OSM_STOP_AREA, sa);
     
    225217        return r;
    226218    }
    227    
     219
    228220    protected LatLon createLatLon(PointType point) {
    229221        return new LatLon(point.getLatitude().doubleValue(), point.getLongitude().doubleValue());
    230222    }
    231    
     223
    232224    protected final <T extends TridentObjectType> T findTridentObject(List<T> list, String id) {
    233225        for (T object : list) {
     
    238230        return null;
    239231    }
    240    
     232
    241233    protected StopPoint findStopPoint(String id) {
    242234        return findTridentObject(root.getChouetteLineDescription().getStopPoint(), id);
     
    311303                            }
    312304                        }
    313                        
     305
    314306                    } else if (childId.contains("StopPoint")) {
    315307                        StopPoint child = findStopPoint(childId);
     
    352344                        addStopToRoute(route, start);
    353345                    }
    354                    
     346
    355347                    if (end == null) {
    356348                        System.err.println("Cannot find end StopPoint: "+ptlink.getEndOfLink());
     
    361353            }
    362354        }
    363        
     355
    364356        return ds;
    365357    }
    366        
     358
    367359    private static final boolean addStopToRoute(Relation route, OsmPrimitive stop) {
    368360        if (route.getMembersCount() == 0 || !route.getMember(route.getMembersCount()-1).getMember().equals(stop) ) {
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/SevenZipReader.java

    r30568 r30738  
    3333
    3434    private final IInArchive archive = new Handler();
    35    
     35
    3636    public SevenZipReader(InputStream in, AbstractDataSetHandler handler, boolean promptUser) throws IOException {
    3737        super(handler, handler != null ? handler.getArchiveHandler() : null, promptUser);
     
    4141            Utils.copyStream(in, out);
    4242        }
    43         IInStream random = new MyRandomAccessFile(tmpFile.getPath(), "r");
    44         if (archive.Open(random) != 0) {
    45             String message = "Unable to open 7z archive: "+tmpFile.getPath();
    46             Main.warn(message);
    47             random.close();
    48             if (!tmpFile.delete()) {
    49                 tmpFile.deleteOnExit();
     43        try (IInStream random = new MyRandomAccessFile(tmpFile.getPath(), "r")) {
     44            if (archive.Open(random) != 0) {
     45                String message = "Unable to open 7z archive: "+tmpFile.getPath();
     46                Main.warn(message);
     47                if (!tmpFile.delete()) {
     48                    tmpFile.deleteOnExit();
     49                }
     50                throw new IOException(message);
    5051            }
    51             throw new IOException(message);
    5252        }
    5353    }
    54    
    55     public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
     54
     55    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
    5656            throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
    5757        return new SevenZipReader(in, handler, promptUser).parseDoc(instance);
    5858    }
    5959
    60     public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
     60    public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
    6161            throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
    6262        return new SevenZipReader(in, handler, promptUser).parseDocs(instance);
     
    7171        archive.Extract(null, -1, IInArchive.NExtract_NAskMode_kExtract, new ExtractCallback(archive, temp, candidates));
    7272    }
    73    
     73
    7474    private class ExtractCallback extends ArchiveExtractCallback {
    7575        private final List<File> candidates;
    76        
     76
    7777        public ExtractCallback(IInArchive archive, File tempDir, List<File> candidates) {
    7878            Init(archive);
     
    8181        }
    8282
    83         @Override 
     83        @Override
    8484        public int GetStream(int index, OutputStream[] outStream, int askExtractMode) throws IOException {
    8585            int res = super.GetStream(index, outStream, askExtractMode);
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/archive/ZipReader.java

    r30723 r30738  
    2626
    2727    private final ZipInputStream zis;
    28    
     28
    2929    private ZipEntry entry;
    30    
     30
    3131    public ZipReader(InputStream in, AbstractDataSetHandler handler, boolean promptUser) {
    3232        super(handler, handler != null ? handler.getArchiveHandler() : null, promptUser);
     
    3434    }
    3535
    36     public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
     36    public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
    3737            throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
    3838        return new ZipReader(in, handler, promptUser).parseDoc(instance);
    3939    }
    4040
    41     public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser) 
     41    public static Map<File, DataSet> parseDataSets(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance, boolean promptUser)
    4242            throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException {
    4343        return new ZipReader(in, handler, promptUser).parseDocs(instance);
    4444    }
    4545
     46    @Override
    4647    protected void extractArchive(final File temp, final List<File> candidates) throws IOException, FileNotFoundException {
    4748        while ((entry = zis.getNextEntry()) != null) {
     
    5859            }
    5960            if (!entry.isDirectory()) {
    60                 if (!file.createNewFile()) { 
     61                if (!file.createNewFile()) {
    6162                    throw new IOException("Could not create temp file: " + file.getAbsolutePath());
    6263                }
    6364                // Write temp file
    64                 FileOutputStream fos = new FileOutputStream(file);
    65                 byte[] buffer = new byte[8192];
    66                 int count = 0;
    67                 while ((count = zis.read(buffer, 0, buffer.length)) > 0) {
    68                     fos.write(buffer, 0, count);
     65                try (FileOutputStream fos = new FileOutputStream(file)) {
     66                    byte[] buffer = new byte[8192];
     67                    int count = 0;
     68                    while ((count = zis.read(buffer, 0, buffer.length)) > 0) {
     69                        fos.write(buffer, 0, count);
     70                    }
    6971                }
    70                 fos.close();
    7172                // Allow handler to perform specific treatments (for example, fix invalid .prj files)
    7273                if (archiveHandler != null) {
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/tabular/CsvImporter.java

    r30723 r30738  
    1818
    1919public class CsvImporter extends AbstractImporter {
    20    
     20
    2121    public static final ExtensionFileFilter CSV_FILE_FILTER = new ExtensionFileFilter(
    2222            OdConstants.CSV_EXT, OdConstants.CSV_EXT, tr("CSV files") + " (*."+OdConstants.CSV_EXT+")");
    23    
     23
    2424    public static final String COLOMBUS_HEADER = "INDEX,TAG,DATE,TIME,LATITUDE N/S,LONGITUDE E/W,HEIGHT,SPEED,HEADING,FIX MODE,VALID,PDOP,HDOP,VDOP,VOX";
    25    
     25
    2626    public CsvImporter() {
    2727        super(CSV_FILE_FILTER);
     
    4646        boolean result = false;
    4747        if (file != null && file.isFile()) {
    48             try {
    49                 BufferedReader reader = new BufferedReader(new FileReader(file));
    50                 try {
    51                     String line = reader.readLine();
    52                     result = line != null && line.equalsIgnoreCase(COLOMBUS_HEADER);
    53                 } finally {
    54                     reader.close();
    55                 }
     48            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
     49                String line = reader.readLine();
     50                result = line != null && line.equalsIgnoreCase(COLOMBUS_HEADER);
    5651            } catch (IOException e) {
    5752                // Ignore exceptions
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ModuleInformation.java

    r30731 r30738  
    7373        this.name = name;
    7474        this.file = file;
    75         FileInputStream fis = null;
    76         JarInputStream jar = null;
    77         try {
    78             fis = new FileInputStream(file);
    79             jar = new JarInputStream(fis);
     75        try (
     76            FileInputStream fis = new FileInputStream(file);
     77            JarInputStream jar = new JarInputStream(fis);
     78        ) {
    8079            Manifest manifest = jar.getManifest();
    8180            if (manifest == null)
     
    8584        } catch (IOException e) {
    8685            throw new ModuleException(name, e);
    87         } finally {
    88             if (jar != null) {
    89                 try {
    90                     jar.close();
    91                 } catch(IOException e) { /* ignore */ }
    92             }
    93             if (fis != null) {
    94                 try {
    95                     fis.close();
    96                 } catch(IOException e) { /* ignore */ }
    97             }
    9886        }
    9987    }
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ReadRemoteModuleInformationTask.java

    r30563 r30738  
    2525import java.util.List;
    2626
     27import org.openstreetmap.josm.Main;
    2728import org.openstreetmap.josm.data.Version;
    2829import org.openstreetmap.josm.gui.PleaseWaitRunnable;
     
    246247     */
    247248    protected void cacheModuleList(String site, String list) {
    248         PrintWriter writer = null;
    249249        try {
    250250            File moduleDir = OdPlugin.getInstance().getModulesDirectory();
    251251            if (!moduleDir.exists()) {
    252252                if (! moduleDir.mkdirs()) {
    253                     System.err.println(tr("Warning: failed to create module directory ''{0}''. Cannot cache module list from module site ''{1}''.", moduleDir.toString(), site));
     253                    Main.warn(tr("Warning: failed to create module directory ''{0}''. Cannot cache module list from module site ''{1}''.",
     254                            moduleDir.toString(), site));
    254255                }
    255256            }
    256257            File cacheFile = createSiteCacheFile(moduleDir, site, CacheType.PLUGIN_LIST);
    257258            getProgressMonitor().subTask(tr("Writing module list to local cache ''{0}''", cacheFile.toString()));
    258             writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), "utf-8"));
    259             writer.write(list);
     259            try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(cacheFile), "utf-8"))) {
     260                writer.write(list);
     261            }
    260262        } catch (IOException e) {
    261263            // just failed to write the cache file. No big deal, but log the exception anyway
    262             e.printStackTrace();
    263         } finally {
    264             if (writer != null) {
    265                 writer.flush();
    266                 writer.close();
    267             }
     264            Main.warn(e);
    268265        }
    269266    }
     
    300297            File [] f = new File(location).listFiles(
    301298                    new FilenameFilter() {
     299                        @Override
    302300                        public boolean accept(File dir, String name) {
    303301                            return name.matches("^([0-9]+-)?site.*\\.txt$") ||
  • applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/util/NamesFrUtils.java

    r30723 r30738  
    1111
    1212import org.apache.commons.lang3.text.WordUtils;
     13import org.openstreetmap.josm.Main;
    1314import org.openstreetmap.josm.data.osm.OsmPrimitive;
    1415import org.openstreetmap.josm.plugins.opendata.core.OdConstants;
     
    1617
    1718public abstract class NamesFrUtils {
    18    
     19
    1920    private static Map<String, String> dictionary = initDictionary();
    2021
     
    2930        return result;
    3031    }
    31    
     32
    3233    private static Map<String, String> initDictionary() {
    3334        Map<String, String> result = new HashMap<>();
    34         try {
    35             BufferedReader reader = new BufferedReader(new InputStreamReader(
    36                     SimpleDataSetHandler.class.getResourceAsStream(OdConstants.DICTIONARY_FR), OdConstants.UTF8));
     35        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
     36                SimpleDataSetHandler.class.getResourceAsStream(OdConstants.DICTIONARY_FR), OdConstants.UTF8))) {
    3737            String line = reader.readLine(); // Skip first line
    3838            while ((line = reader.readLine()) != null) {
     
    4040                result.put(tab[0].replace("\"", ""), tab[1].replace("\"", ""));
    4141            }
    42             reader.close();
    4342        } catch (IOException e) {
    44             e.printStackTrace();
     43            Main.error(e);
    4544        }
    4645        return result;
     
    170169            if (value != null) {
    171170                value = WordUtils.capitalizeFully(value);
    172                 // Cas particuliers 
     171                // Cas particuliers
    173172                if (value.equals("Boulingrin")) { // square Boulingrin, mal formé
    174173                    value = "Sq Boulingrin";
  • applications/editors/josm/plugins/opendata/util/opendata/ModuleListGenerator.java

    r30340 r30738  
    1515import java.util.zip.ZipOutputStream;
    1616
     17import org.openstreetmap.josm.Main;
     18
    1719public class ModuleListGenerator {
    1820
     
    2628                        baseDir = args[0];
    2729                }
    28                 try {
     30                try (
    2931                        BufferedWriter list = new BufferedWriter(new FileWriter(baseDir+"modules.txt"));
    3032                        ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(baseDir+"modules-icons.zip"));
     33                ) {
    3134                        for (File file : new File(baseDir+"dist").listFiles(new FilenameFilter() {
    3235                                @Override
     
    3740                                try {
    3841                                        String filename = file.getName();
    39                                         System.out.println("Processing "+filename);
     42                                        Main.info("Processing "+filename);
    4043                                        list.write(filename+";"+url+filename); list.newLine();
    4144                                        Manifest mf = new JarFile(file).getManifest();
     
    7780                                                                        }
    7881                                                                } catch (IOException e) {
    79                                                                         System.err.println("Cannot load Image-Icon: "+value.toString());
     82                                                                        Main.error("Cannot load Image-Icon: "+value.toString());
    8083                                                                } finally {
    8184                                                                        zip.closeEntry();
     
    8487                                                }
    8588                                        }
    86                                        
     89
    8790                                } catch (IOException e) {
    88                                         e.printStackTrace();
     91                                    Main.error(e);
    8992                                }
    9093                        }
    91                         System.out.println("Done");
    92                         zip.close();
    93                         list.close();
    9494                } catch (IOException e) {
    95                         e.printStackTrace();
     95                        Main.error(e);
    9696                }
    9797        }
  • applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java

    r30737 r30738  
    5454
    5555        @Override
    56                 public void actionPerformed(ActionEvent e) {
     56        public void actionPerformed(ActionEvent e) {
    5757            DataSet ds = Main.main.getCurrentDataSet();
    5858            if (ds == null) {
    5959                return;
    6060            }
    61            
     61
    6262            // get all stuff visible on screen
    6363            LatLon bottomLeft = Main.map.mapView.getLatLon(0,Main.map.mapView.getHeight());
     
    6767            try {
    6868                writeGenerated(b);
    69             } catch(Exception ex) {
    70                 //how handle the exception?
    71             }
    72 
     69            } catch (Exception ex) {
     70                // how handle the exception?
     71                Main.error(ex);
     72            }
    7373
    7474            String firefox = Main.pref.get("osmarender.firefox", "firefox");
    75             try {
     75            try (OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(new OutputStreamWriter(
     76                    new FileOutputStream(getPluginDir()+File.separator+"data.osm"), "UTF-8")), false, "0.6")) {
    7677                // write to plugin dir
    77                 OsmWriter w = OsmWriterFactory.createOsmWriter(new PrintWriter(new OutputStreamWriter(
    78                         new FileOutputStream(getPluginDir()+File.separator+"data.osm"), "UTF-8")), false, "0.6");
    7978                w.header();
    8079
     
    116115
    117116                // get the exec line
    118                 String argument; 
     117                String argument;
    119118                if (Main.platform instanceof PlatformHookWindows)
    120119                    argument = "file:///"+getPluginDir().replace('\\','/').replace(" ","%20")+File.separator+"generated.xml\"";
     
    198197            "maxlon=\"" + b.getMax().lon() + "\" " + "/>";
    199198
    200         BufferedReader reader = new BufferedReader(
    201                 new FileReader( getPluginDir() + File.separator + "osm-map-features.xml") );
    202         PrintWriter writer = new PrintWriter( getPluginDir() + File.separator + "generated.xml", "UTF-8");
    203 
    204         // osm-map-features.xml contain two placemark
    205         // (bounds_mkr1 and bounds_mkr2). We write the bounds tag
    206         // between the two
    207         String str = null;
    208         while( (str = reader.readLine()) != null ) {
    209             if(str.contains("<!--bounds_mkr1-->")) {
    210                 writer.println(str);
    211                 writer.println("    " + bounds_tag);
    212                 while(!str.contains("<!--bounds_mkr2-->")) {
    213                     str = reader.readLine();
    214                 }
    215                 writer.println(str);
    216             } else {
    217                 writer.println(str);
    218             }
    219         }
    220 
    221         writer.close();
    222         reader.close();
     199        try (
     200            BufferedReader reader = new BufferedReader(
     201                    new FileReader( getPluginDir() + File.separator + "osm-map-features.xml") );
     202            PrintWriter writer = new PrintWriter( getPluginDir() + File.separator + "generated.xml", "UTF-8");
     203        ) {
     204            // osm-map-features.xml contain two placemark
     205            // (bounds_mkr1 and bounds_mkr2). We write the bounds tag between the two
     206            String str = null;
     207            while( (str = reader.readLine()) != null ) {
     208                if(str.contains("<!--bounds_mkr1-->")) {
     209                    writer.println(str);
     210                    writer.println("    " + bounds_tag);
     211                    while(!str.contains("<!--bounds_mkr2-->")) {
     212                        str = reader.readLine();
     213                    }
     214                    writer.println(str);
     215                } else {
     216                    writer.println(str);
     217                }
     218            }
     219        }
    223220    }
    224221}
  • applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/ExifGPSTagger.java

    r28398 r30738  
    88import java.io.FileOutputStream;
    99import java.io.IOException;
    10 import java.io.OutputStream;
    1110import java.text.DecimalFormat;
    1211import java.util.Calendar;
     
    4948    }
    5049
    51     public static void setExifGPSTagWorker(File jpegImageFile, File dst, double lat, double lon, long gpsTime, Double ele) throws IOException,
    52             ImageReadException, ImageWriteException
    53     {
    54         OutputStream os = null;
    55         try {
    56             TiffOutputSet outputSet = null;
     50    public static void setExifGPSTagWorker(File jpegImageFile, File dst, double lat, double lon, long gpsTime, Double ele)
     51            throws IOException, ImageReadException, ImageWriteException {
     52        TiffOutputSet outputSet = null;
    5753
    58             IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
    59             JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
    60             if (null != jpegMetadata) {
    61                 TiffImageMetadata exif = jpegMetadata.getExif();
     54        IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile);
     55        JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
     56        if (null != jpegMetadata) {
     57            TiffImageMetadata exif = jpegMetadata.getExif();
    6258
    63                 if (null != exif) {
    64                     outputSet = exif.getOutputSet();
    65                 }
     59            if (null != exif) {
     60                outputSet = exif.getOutputSet();
    6661            }
     62        }
    6763
    68             if (null == outputSet) {
    69                 outputSet = new TiffOutputSet();
    70             }
     64        if (null == outputSet) {
     65            outputSet = new TiffOutputSet();
     66        }
    7167
    72             Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
     68        Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    7369
    74             calendar.setTimeInMillis(gpsTime);
     70        calendar.setTimeInMillis(gpsTime);
    7571
    76             final int year =   calendar.get(Calendar.YEAR);
    77             final int month =  calendar.get(Calendar.MONTH) + 1;
    78             final int day =    calendar.get(Calendar.DAY_OF_MONTH);
    79             final int hour =   calendar.get(Calendar.HOUR_OF_DAY);
    80             final int minute = calendar.get(Calendar.MINUTE);
    81             final int second = calendar.get(Calendar.SECOND);
     72        final int year =   calendar.get(Calendar.YEAR);
     73        final int month =  calendar.get(Calendar.MONTH) + 1;
     74        final int day =    calendar.get(Calendar.DAY_OF_MONTH);
     75        final int hour =   calendar.get(Calendar.HOUR_OF_DAY);
     76        final int minute = calendar.get(Calendar.MINUTE);
     77        final int second = calendar.get(Calendar.SECOND);
    8278
    83             DecimalFormat yearFormatter = new DecimalFormat("0000");
    84             DecimalFormat monthFormatter = new DecimalFormat("00");
    85             DecimalFormat dayFormatter = new DecimalFormat("00");
     79        DecimalFormat yearFormatter = new DecimalFormat("0000");
     80        DecimalFormat monthFormatter = new DecimalFormat("00");
     81        DecimalFormat dayFormatter = new DecimalFormat("00");
    8682
    87             final String yearStr = yearFormatter.format(year);
    88             final String monthStr = monthFormatter.format(month);
    89             final String dayStr = dayFormatter.format(day);
    90             final String dateStamp = yearStr+":"+monthStr+":"+dayStr;
    91             //System.err.println("date: "+dateStamp+"  h/m/s: "+hour+"/"+minute+"/"+second);
     83        final String yearStr = yearFormatter.format(year);
     84        final String monthStr = monthFormatter.format(month);
     85        final String dayStr = dayFormatter.format(day);
     86        final String dateStamp = yearStr+":"+monthStr+":"+dayStr;
     87        //System.err.println("date: "+dateStamp+"  h/m/s: "+hour+"/"+minute+"/"+second);
    9288
    93             Double[] timeStamp = {new Double(hour), new Double(minute), new Double(second)};
    94             TiffOutputField gpsTimeStamp = TiffOutputField.create(
    95                     GPSTagConstants.GPS_TAG_GPS_TIME_STAMP,
    96                     outputSet.byteOrder, timeStamp);
    97             TiffOutputDirectory exifDirectory = outputSet.getOrCreateGPSDirectory();
    98             // make sure to remove old value if present (this method will
    99             // not fail if the tag does not exist).
    100             exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_TIME_STAMP);
    101             exifDirectory.add(gpsTimeStamp);
     89        Double[] timeStamp = {new Double(hour), new Double(minute), new Double(second)};
     90        TiffOutputField gpsTimeStamp = TiffOutputField.create(
     91                GPSTagConstants.GPS_TAG_GPS_TIME_STAMP,
     92                outputSet.byteOrder, timeStamp);
     93        TiffOutputDirectory exifDirectory = outputSet.getOrCreateGPSDirectory();
     94        // make sure to remove old value if present (this method will
     95        // not fail if the tag does not exist).
     96        exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_TIME_STAMP);
     97        exifDirectory.add(gpsTimeStamp);
    10298
    103             TiffOutputField gpsDateStamp = SanselanFixes.create(
    104                     GPSTagConstants.GPS_TAG_GPS_DATE_STAMP,
    105                     outputSet.byteOrder, dateStamp);
    106             // make sure to remove old value if present (this method will
    107             // not fail if the tag does not exist).
    108             exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_DATE_STAMP);
    109             exifDirectory.add(gpsDateStamp);
     99        TiffOutputField gpsDateStamp = SanselanFixes.create(
     100                GPSTagConstants.GPS_TAG_GPS_DATE_STAMP,
     101                outputSet.byteOrder, dateStamp);
     102        // make sure to remove old value if present (this method will
     103        // not fail if the tag does not exist).
     104        exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_DATE_STAMP);
     105        exifDirectory.add(gpsDateStamp);
    110106
    111             SanselanFixes.setGPSInDegrees(outputSet, lon, lat);
     107        SanselanFixes.setGPSInDegrees(outputSet, lon, lat);
    112108
    113             if (ele != null) {
    114                 byte eleRef =  ele >= 0 ? (byte) 0 : (byte) 1;
    115                 TiffOutputField gpsAltitudeRef = new TiffOutputField(
    116                         GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF,
    117                         FieldType.FIELD_TYPE_BYTE, 1, new byte[] { eleRef });
    118                 exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
    119                 exifDirectory.add(gpsAltitudeRef);
     109        if (ele != null) {
     110            byte eleRef =  ele >= 0 ? (byte) 0 : (byte) 1;
     111            TiffOutputField gpsAltitudeRef = new TiffOutputField(
     112                    GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF,
     113                    FieldType.FIELD_TYPE_BYTE, 1, new byte[] { eleRef });
     114            exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE_REF);
     115            exifDirectory.add(gpsAltitudeRef);
    120116
    121                 Number[] val = new Number[] { Math.abs(ele) };
    122                 byte[] bytes = FieldType.FIELD_TYPE_RATIONAL.writeData(val, outputSet.byteOrder);
    123                 TiffOutputField gpsAltitude = new TiffOutputField(
    124                         GPSTagConstants.GPS_TAG_GPS_ALTITUDE,
    125                         FieldType.FIELD_TYPE_RATIONAL, 1, bytes);
    126                 exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE);
    127                 exifDirectory.add(gpsAltitude);
    128             }
    129 
    130             os = new FileOutputStream(dst);
    131             os = new BufferedOutputStream(os);
    132 
    133             new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os,
    134                     outputSet);
    135 
    136             os.close();
    137             os = null;
    138         } finally {
    139             if (os != null) {
    140                 try {
    141                     os.close();
    142                 } catch (IOException e) {}
    143             }
     117            Number[] val = new Number[] { Math.abs(ele) };
     118            byte[] bytes = FieldType.FIELD_TYPE_RATIONAL.writeData(val, outputSet.byteOrder);
     119            TiffOutputField gpsAltitude = new TiffOutputField(
     120                    GPSTagConstants.GPS_TAG_GPS_ALTITUDE,
     121                    FieldType.FIELD_TYPE_RATIONAL, 1, bytes);
     122            exifDirectory.removeField(GPSTagConstants.GPS_TAG_GPS_ALTITUDE);
     123            exifDirectory.add(gpsAltitude);
     124        }
     125        try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(dst))) {
     126            new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet);
    144127        }
    145128    }
  • applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/layer/PicLayerFromFile.java

    r30436 r30738  
    7474
    7575        if (isZip) {
    76             ZipFile zipFile = null;
    77             try
    78             {
    79                 zipFile = new ZipFile(m_file);
     76            try (ZipFile zipFile = new ZipFile(m_file)) {
    8077                ZipEntry imgEntry = null;
    8178                Enumeration<? extends ZipEntry> entries = zipFile.entries();
     
    103100                System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString()));
    104101                return null;
    105             } finally {
    106                 if (zipFile != null) {
    107                     try {
    108                         zipFile.close();
    109                     } catch (IOException ex) {
    110                     }
    111                 }
    112102            }
    113103        } else {
     
    149139
    150140        if (isZip) {
    151             ZipFile zipFile = null;
    152             try
    153             {
    154                 zipFile = new ZipFile(m_file);
     141            try (ZipFile zipFile = new ZipFile(m_file)) {
    155142                String calFileStr = imgNameInZip + CalibrationFileFilter.EXTENSION;
    156143                ZipEntry calEntry = zipFile.getEntry(calFileStr);
     
    183170                }
    184171            } catch (Exception e) {
    185                 System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString()));
     172                Main.warn(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString()));
    186173                return;
    187             } finally {
    188                 if (zipFile != null) {
    189                     try {
    190                         zipFile.close();
    191                     } catch (IOException ex) {
    192                     }
    193                 }
    194174            }
    195175        } else {
  • applications/editors/josm/plugins/poly/src/poly/PolyExporter.java

    r30737 r30738  
    2525/**
    2626 * Writes poly files.
    27  * 
     27 *
    2828 * @author zverik
    2929 */
     
    3737    public void exportData( File file, Layer layer ) throws IOException {
    3838        if( layer instanceof OsmDataLayer ) {
    39             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
    40             try {
     39            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"))) {
    4140                DataSet ds = ((OsmDataLayer)layer).data;
    4241                Map<Way, Boolean> ways = new TreeMap<>();
     
    7170                writer.write("END");
    7271                writer.newLine();
    73             } finally {
    74                 writer.close();
    7572            }
    7673        }
  • applications/editors/josm/plugins/poly/src/poly/PolyImporter.java

    r30737 r30738  
    11package poly;
     2
     3import static org.openstreetmap.josm.tools.I18n.tr;
    24
    35import java.io.BufferedReader;
     
    79import java.util.ArrayList;
    810import java.util.List;
     11
    912import javax.swing.JOptionPane;
     13
    1014import org.openstreetmap.josm.Main;
    1115import org.openstreetmap.josm.data.coor.LatLon;
    12 
    13 import static org.openstreetmap.josm.tools.I18n.tr;
    1416import org.openstreetmap.josm.data.osm.DataSet;
    1517import org.openstreetmap.josm.data.osm.Node;
     
    1921import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
    2022import org.openstreetmap.josm.gui.progress.ProgressMonitor;
     23import org.openstreetmap.josm.io.CachedFile;
    2124import org.openstreetmap.josm.io.IllegalDataException;
    22 import org.openstreetmap.josm.io.CachedFile;
    2325import org.openstreetmap.josm.io.OsmImporter;
    2426import org.openstreetmap.josm.tools.CheckParameterUtil;
     
    4446            progressMonitor = NullProgressMonitor.INSTANCE;
    4547        CheckParameterUtil.ensureParameterNotNull(in, "in");
    46         BufferedReader reader = null;
    47 
    48         try {
     48
     49        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8"))) {
    4950            progressMonitor.beginTask(tr("Reading polygon filter file..."), 2);
    5051            progressMonitor.indeterminateSubTask(tr("Reading polygon filter file..."));
    51             reader = new BufferedReader(new InputStreamReader(in, "UTF8"));
    5252            List<Area> areas = loadPolygon(reader);
    5353            progressMonitor.worked(1);
    54            
     54
    5555            progressMonitor.indeterminateSubTask(tr("Preparing data set..."));
    5656            DataSet ds = constructDataSet(areas);
     
    6060            throw new IllegalDataException(tr("Error reading poly file: {0}", e.getMessage()), e);
    6161        } finally {
    62             try {
    63                 if( reader != null )
    64                     reader.close();
    65             } catch( IOException e ) { }
    6662            progressMonitor.finishTask();
    6763        }
    6864    }
    69    
     65
    7066    private List<Area> loadPolygon( BufferedReader reader ) throws IllegalDataException, IOException {
    7167        String name = reader.readLine();
     
    145141        DataSet ds = new DataSet();
    146142        ds.setUploadDiscouraged(true);
    147        
     143
    148144        boolean foundInner = false;
    149145        for( Area area : areas ) {
  • applications/editors/josm/plugins/proj4j/src/org/openstreetmap/josm/plugins/proj4j/Proj4JProjectionChoice.java

    r30737 r30738  
    6464        sorter = new TableRowSorter<>(model);
    6565    }
    66    
     66
    6767    @Override
    6868    public String getId() {
     
    7474        return new Proj4JPanel(actionListener);
    7575    }
    76    
     76
    7777    protected class Proj4JPanel extends JPanel {
    78        
     78
    7979        public Proj4JPanel(ActionListener actionListener) {
    8080            GridBagConstraints c = new GridBagConstraints();
     
    9494                    new DocumentListener() {
    9595
     96                        @Override
    9697                        public void insertUpdate(DocumentEvent e) {
    9798                            newFilter();
    9899                        }
    99100
     101                        @Override
    100102                        public void removeUpdate(DocumentEvent e) {
    101103                            newFilter();
    102104                        }
    103105
     106                        @Override
    104107                        public void changedUpdate(DocumentEvent e) {
    105108                            newFilter();
     
    213216        }
    214217
     218        @Override
    215219        public void valueChanged(ListSelectionEvent e) {
    216220            updateSelectedCode();
     
    258262        public CRSTableModel() throws java.io.IOException {
    259263            // Read projection information from file, (authority, code, description)
    260             InputStream inStr = getClass().getResourceAsStream("/resources/projections.txt");
    261             BufferedReader fh = new BufferedReader(new InputStreamReader(inStr));
    262 
    263             String s;
    264             while ((s = fh.readLine()) != null) {
    265                 String f[] = s.split("\t");
    266                 if (f.length >= 3) {
    267                     crsList.add(new CRSEntry(f[0], f[1], f[2]));
     264            try (
     265                InputStream inStr = getClass().getResourceAsStream("/resources/projections.txt");
     266                BufferedReader fh = new BufferedReader(new InputStreamReader(inStr));
     267            ) {
     268                String s;
     269                while ((s = fh.readLine()) != null) {
     270                    String f[] = s.split("\t");
     271                    if (f.length >= 3) {
     272                        crsList.add(new CRSEntry(f[0], f[1], f[2]));
     273                    }
    268274                }
    269275            }
    270             fh.close();
    271276        }
    272277
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelation.java

    r30737 r30738  
    150150                }
    151151            } else if( element.getType() == OsmPrimitiveType.RELATION ) {
    152                 Color oldColor = g.getColor();
    153                 g.setColor(Color.magenta);
     152                Color oldColor = g.getColor();
     153                g.setColor(Color.magenta);
    154154                drawRelations(g, mv, bbox, (Relation)element);
    155155                g.setColor(oldColor);
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelationListener.java

    r25649 r30738  
    99 */
    1010public interface ChosenRelationListener {
    11         void chosenRelationChanged( Relation oldRelation, Relation newRelation );
     11    void chosenRelationChanged( Relation oldRelation, Relation newRelation );
    1212}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/ExtraNameFormatHook.java

    r26802 r30738  
    1414
    1515    public String checkRelationTypeName( IRelation relation, String defaultName ) {
    16         return null;
     16    return null;
    1717    }
    1818
    1919    public String checkFormat( INode node, String defaultName ) {
    20         return null;
     20    return null;
    2121    }
    2222
    2323    public String checkFormat( IWay way, String defaultName ) {
    24         if( way.get("place") != null && way.get("name") == null && way.get("place_name") != null )
    25             return way.get("place_name") + " " + defaultName;
    26         return null;
     24    if( way.get("place") != null && way.get("name") == null && way.get("place_name") != null )
     25        return way.get("place_name") + " " + defaultName;
     26    return null;
    2727    }
    2828
    2929    public String checkFormat( IRelation relation, String defaultName ) {
    30         String type = relation.get("type");
    31         if( type != null ) {
    32             String name = relation.get("destination");
    33             if( type.equals("destination_sign") && name != null ) {
    34                 if( relation.get("distance") != null )
    35                     name += " " + relation.get("distance");
    36                 if( defaultName.indexOf('"') < 0 )
    37                     return '"' + name + "\" " + defaultName;
    38                 else
    39                     return defaultName.replaceFirst("\".?+\"", '"'+name+'"');
    40             }
    41         }
    42         return null;
     30    String type = relation.get("type");
     31    if( type != null ) {
     32        String name = relation.get("destination");
     33        if( type.equals("destination_sign") && name != null ) {
     34        if( relation.get("distance") != null )
     35            name += " " + relation.get("distance");
     36        if( defaultName.indexOf('"') < 0 )
     37            return '"' + name + "\" " + defaultName;
     38        else
     39            return defaultName.replaceFirst("\".?+\"", '"'+name+'"');
     40        }
     41    }
     42    return null;
    4343    }
    4444}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextDialog.java

    r30737 r30738  
    9797/**
    9898 * The new, advanced relation editing panel.
    99  * 
     99 *
    100100 * @author Zverik
    101101 */
     
    103103
    104104    public final static String PREF_PREFIX = "reltoolbox";
    105    
     105
    106106    private final DefaultTableModel relationsData;
    107107    private ChosenRelation chosenRelation;
     
    142142        roleBox.addMouseListener(relationMouseAdapter);
    143143        roleBox.addItemListener(new ItemListener() {
     144            @Override
    144145            public void itemStateChanged( ItemEvent e ) {
    145146                if( e.getStateChange() == ItemEvent.DESELECTED ) return;
     
    174175
    175176        roleBox.addPropertyChangeListener("enabled", new PropertyChangeListener() {
     177            @Override
    176178            public void propertyChange( PropertyChangeEvent evt ) {
    177179                boolean showRoleBox = roleBox.isEnabled();
     
    182184
    183185        sortAndFixAction.addPropertyChangeListener(new PropertyChangeListener() {
     186            @Override
    184187            public void propertyChange( PropertyChangeEvent evt ) {
    185188                sortAndFixButton.setVisible(sortAndFixAction.isEnabled());
     
    189192
    190193        downloadChosenRelationAction.addPropertyChangeListener(new PropertyChangeListener() {
     194            @Override
    191195            public void propertyChange( PropertyChangeEvent evt ) {
    192196                downloadButton.setVisible(downloadChosenRelationAction.isEnabled());
     
    304308        columns.getColumn(0).setPreferredWidth(220);
    305309        relationsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
     310            @Override
    306311            public void valueChanged( ListSelectionEvent e ) {
    307312                int selectedRow = relationsTable.getSelectedRow();
     
    339344    }
    340345
     346    @Override
    341347    public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) {
    342348        if( chosenRelationPanel != null && Main.pref.getBoolean(PREF_PREFIX + ".hidetopline", false) )
     
    348354    }
    349355
     356    @Override
    350357    public void selectionChanged( Collection<? extends OsmPrimitive> newSelection ) {
    351358        if( !isVisible() || relationsData == null )
     
    397404    }
    398405
     406    @Override
    399407    public void editLayerChanged( OsmDataLayer oldLayer, OsmDataLayer newLayer ) {
    400408        updateSelection();
     
    410418        super.destroy();
    411419    }
    412    
     420
    413421    private static final String POSSIBLE_ROLES_FILE = "relcontext/possible_roles.txt";
    414422    private static final Map<String, List<String>> possibleRoles = loadRoles();
     
    416424    private static Map<String, List<String>> loadRoles() {
    417425        Map<String, List<String>> result = new HashMap<>();
    418         try {
    419             ClassLoader classLoader = RelContextDialog.class.getClassLoader();
    420             final InputStream possibleRolesStream = classLoader.getResourceAsStream(POSSIBLE_ROLES_FILE);
     426        ClassLoader classLoader = RelContextDialog.class.getClassLoader();
     427        try (
     428            InputStream possibleRolesStream = classLoader.getResourceAsStream(POSSIBLE_ROLES_FILE);
    421429            BufferedReader r = new BufferedReader(new InputStreamReader(possibleRolesStream));
     430        ) {
    422431            while( r.ready() ) {
    423432                String line = r.readLine();
     
    431440                }
    432441            }
    433             r.close();
    434442        } catch( Exception e ) {
    435             System.err.println("[RelToolbox] Error reading possible roles file.");
    436             e.printStackTrace();
     443            Main.error("[RelToolbox] Error reading possible roles file.");
     444            Main.error(e);
    437445        }
    438446        return result;
     
    466474
    467475        role.getEditor().addActionListener(new ActionListener() {
     476            @Override
    468477            public void actionPerformed( ActionEvent e ) {
    469478                dlg.setVisible(false);
     
    589598        }
    590599
     600        @Override
    591601        public void actionPerformed( ActionEvent e ) {
    592602            String property = e.getActionCommand();
     
    609619        }
    610620
     621        @Override
    611622        public void actionPerformed( ActionEvent e ) {
    612623            if( roleBoxModel.membersRole != null ) {
     
    617628        }
    618629
     630        @Override
    619631        public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) {
    620632            setEnabled(newRelation != null);
    621633        }
    622634    }
    623        
     635
    624636    private class RoleComboBoxModel extends AbstractListModel<String> implements ComboBoxModel<String> {
    625637        private List<String> roles = new ArrayList<>();
     
    704716        }
    705717
     718        @Override
    706719        public int getSize() {
    707720            return roles.size();
    708721        }
    709722
     723        @Override
    710724        public String getElementAt( int index ) {
    711725            return getRole(index);
     
    716730        }
    717731
     732        @Override
    718733        public void setSelectedItem( Object anItem ) {
    719734            int newIndex = anItem == null ? -1 : roles.indexOf(anItem);
     
    724739        }
    725740
     741        @Override
    726742        public Object getSelectedItem() {
    727743            return selectedIndex < 0 || selectedIndex >= getSize() ? null : getRole(selectedIndex);
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextPlugin.java

    r29535 r30738  
    1111    public RelContextPlugin( PluginInformation info ) {
    1212        super(info);
    13         DefaultNameFormatter.registerFormatHook(new ExtraNameFormatHook());
     13    DefaultNameFormatter.registerFormatHook(new ExtraNameFormatHook());
    1414    }
    1515
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/CreateMultipolygonAction.java

    r30737 r30738  
    2828
    2929    public CreateMultipolygonAction( ChosenRelation chRel ) {
    30         super("Multi", "data/multipolygon", tr("Create a multipolygon from selected objects"),
    31                 Shortcut.registerShortcut("reltoolbox:multipolygon", tr("Relation Toolbox: {0}", tr("Create multipolygon")),
    32                 KeyEvent.VK_A, Shortcut.ALT_CTRL), false);
    33         this.chRel = chRel;
    34         updateEnabledState();
     30    super("Multi", "data/multipolygon", tr("Create a multipolygon from selected objects"),
     31        Shortcut.registerShortcut("reltoolbox:multipolygon", tr("Relation Toolbox: {0}", tr("Create multipolygon")),
     32        KeyEvent.VK_A, Shortcut.ALT_CTRL), false);
     33    this.chRel = chRel;
     34    updateEnabledState();
    3535    }
    3636
    3737    public CreateMultipolygonAction() {
    38         this(null);
     38    this(null);
    3939    }
    4040
    4141    public static boolean getDefaultPropertyValue( String property ) {
    42         if( property.equals("boundary") )
    43             return false;
    44         else if( property.equals("boundaryways") )
    45             return true;
    46         else if( property.equals("tags") )
    47             return true;
    48         else if( property.equals("alltags") )
    49             return false;
    50         else if( property.equals("single") )
    51             return true;
    52         else if( property.equals("allowsplit") )
    53             return false;
    54         throw new IllegalArgumentException(property);
     42    if( property.equals("boundary") )
     43        return false;
     44    else if( property.equals("boundaryways") )
     45        return true;
     46    else if( property.equals("tags") )
     47        return true;
     48    else if( property.equals("alltags") )
     49        return false;
     50    else if( property.equals("single") )
     51        return true;
     52    else if( property.equals("allowsplit") )
     53        return false;
     54    throw new IllegalArgumentException(property);
    5555    }
    5656
    5757    private boolean getPref( String property ) {
    58         return Main.pref.getBoolean(PREF_MULTIPOLY + property, getDefaultPropertyValue(property));
     58    return Main.pref.getBoolean(PREF_MULTIPOLY + property, getDefaultPropertyValue(property));
    5959    }
    6060
    6161    public void actionPerformed( ActionEvent e ) {
    62         boolean isBoundary = getPref("boundary");
    63         Collection<Way> selectedWays = getCurrentDataSet().getSelectedWays();
    64         if( !isBoundary && getPref("tags") ) {
    65             List<Relation> rels = null;
    66             if( getPref("allowsplit") || selectedWays.size() == 1 ) {
    67                 if( SplittingMultipolygons.canProcess(selectedWays) )
    68                     rels = SplittingMultipolygons.process(getCurrentDataSet().getSelectedWays());
    69             } else {
    70                 if( TheRing.areAllOfThoseRings(selectedWays) ) {
    71                     List<Command> commands = new ArrayList<>();
    72                     rels = TheRing.makeManySimpleMultipolygons(getCurrentDataSet().getSelectedWays(), commands);
    73                     if( !commands.isEmpty() )
    74                         Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygons from rings"), commands));
    75                 }
    76             }
    77             if( rels != null && !rels.isEmpty() ) {
    78                 if( chRel != null )
    79                     chRel.set(rels.size() == 1 ? rels.get(0) : null);
    80                 if( rels.size() == 1 )
    81                     getCurrentDataSet().setSelected(rels);
    82                 else
    83                     getCurrentDataSet().clearSelection();
    84                 return;
    85             }
    86         }
    87 
    88         // for now, just copying standard action
    89         MultipolygonBuilder mpc = new MultipolygonBuilder();
    90         String error = mpc.makeFromWays(getCurrentDataSet().getSelectedWays());
    91         if( error != null ) {
    92             JOptionPane.showMessageDialog(Main.parent, error);
    93             return;
    94         }
    95         Relation rel = new Relation();
    96         if( isBoundary ) {
    97             rel.put("type", "boundary");
    98             rel.put("boundary", "administrative");
    99         } else
    100             rel.put("type", "multipolygon");
    101         for( MultipolygonBuilder.JoinedPolygon poly : mpc.outerWays )
    102             for( Way w : poly.ways )
    103                 rel.addMember(new RelationMember("outer", w));
    104         for( MultipolygonBuilder.JoinedPolygon poly : mpc.innerWays )
    105             for( Way w : poly.ways )
    106                 rel.addMember(new RelationMember("inner", w));
    107         List<Command> list = removeTagsFromInnerWays(rel);
    108         if( !list.isEmpty() && isBoundary ) {
    109             Main.main.undoRedo.add(new SequenceCommand(tr("Move tags from ways to relation"), list));
    110             list = new ArrayList<>();
    111         }
    112         if( isBoundary ) {
    113             if( !askForAdminLevelAndName(rel) )
    114                 return;
    115             addBoundaryMembers(rel);
    116             if( getPref("boundaryways") )
    117                 list.addAll(fixWayTagsForBoundary(rel));
    118         }
    119         list.add(new AddCommand(rel));
    120         Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygon"), list));
    121 
    122         if( chRel != null )
    123             chRel.set(rel);
    124 
    125         getCurrentDataSet().setSelected(rel);
     62    boolean isBoundary = getPref("boundary");
     63    Collection<Way> selectedWays = getCurrentDataSet().getSelectedWays();
     64    if( !isBoundary && getPref("tags") ) {
     65        List<Relation> rels = null;
     66        if( getPref("allowsplit") || selectedWays.size() == 1 ) {
     67        if( SplittingMultipolygons.canProcess(selectedWays) )
     68            rels = SplittingMultipolygons.process(getCurrentDataSet().getSelectedWays());
     69        } else {
     70        if( TheRing.areAllOfThoseRings(selectedWays) ) {
     71            List<Command> commands = new ArrayList<>();
     72            rels = TheRing.makeManySimpleMultipolygons(getCurrentDataSet().getSelectedWays(), commands);
     73            if( !commands.isEmpty() )
     74            Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygons from rings"), commands));
     75        }
     76        }
     77        if( rels != null && !rels.isEmpty() ) {
     78        if( chRel != null )
     79            chRel.set(rels.size() == 1 ? rels.get(0) : null);
     80        if( rels.size() == 1 )
     81            getCurrentDataSet().setSelected(rels);
     82        else
     83            getCurrentDataSet().clearSelection();
     84        return;
     85        }
     86    }
     87
     88    // for now, just copying standard action
     89    MultipolygonBuilder mpc = new MultipolygonBuilder();
     90    String error = mpc.makeFromWays(getCurrentDataSet().getSelectedWays());
     91    if( error != null ) {
     92        JOptionPane.showMessageDialog(Main.parent, error);
     93        return;
     94    }
     95    Relation rel = new Relation();
     96    if( isBoundary ) {
     97        rel.put("type", "boundary");
     98        rel.put("boundary", "administrative");
     99    } else
     100        rel.put("type", "multipolygon");
     101    for( MultipolygonBuilder.JoinedPolygon poly : mpc.outerWays )
     102        for( Way w : poly.ways )
     103        rel.addMember(new RelationMember("outer", w));
     104    for( MultipolygonBuilder.JoinedPolygon poly : mpc.innerWays )
     105        for( Way w : poly.ways )
     106        rel.addMember(new RelationMember("inner", w));
     107    List<Command> list = removeTagsFromInnerWays(rel);
     108    if( !list.isEmpty() && isBoundary ) {
     109        Main.main.undoRedo.add(new SequenceCommand(tr("Move tags from ways to relation"), list));
     110        list = new ArrayList<>();
     111    }
     112    if( isBoundary ) {
     113        if( !askForAdminLevelAndName(rel) )
     114        return;
     115        addBoundaryMembers(rel);
     116        if( getPref("boundaryways") )
     117        list.addAll(fixWayTagsForBoundary(rel));
     118    }
     119    list.add(new AddCommand(rel));
     120    Main.main.undoRedo.add(new SequenceCommand(tr("Create multipolygon"), list));
     121
     122    if( chRel != null )
     123        chRel.set(rel);
     124
     125    getCurrentDataSet().setSelected(rel);
    126126    }
    127127
    128128    @Override
    129129    protected void updateEnabledState() {
    130         if( getCurrentDataSet() == null ) {
    131             setEnabled(false);
    132         } else {
    133             updateEnabledState(getCurrentDataSet().getSelected());
    134         }
     130    if( getCurrentDataSet() == null ) {
     131        setEnabled(false);
     132    } else {
     133        updateEnabledState(getCurrentDataSet().getSelected());
     134    }
    135135    }
    136136
    137137    @Override
    138138    protected void updateEnabledState( Collection<? extends OsmPrimitive> selection ) {
    139         boolean isEnabled = true;
    140         if( selection == null || selection.isEmpty() )
    141             isEnabled = false;
    142         else {
    143             if( !getPref("boundary") ) {
    144                 for( OsmPrimitive p : selection ) {
    145                     if( !(p instanceof Way) ) {
    146                         isEnabled = false;
    147                         break;
    148                     }
    149                 }
    150             }
    151         }
    152         setEnabled(isEnabled);
     139    boolean isEnabled = true;
     140    if( selection == null || selection.isEmpty() )
     141        isEnabled = false;
     142    else {
     143        if( !getPref("boundary") ) {
     144        for( OsmPrimitive p : selection ) {
     145            if( !(p instanceof Way) ) {
     146            isEnabled = false;
     147            break;
     148            }
     149        }
     150        }
     151    }
     152    setEnabled(isEnabled);
    153153    }
    154154
     
    157157     */
    158158    private void addBoundaryMembers( Relation rel ) {
    159         for( OsmPrimitive p : getCurrentDataSet().getSelected() ) {
    160             String role = null;
    161             if( p.getType().equals(OsmPrimitiveType.RELATION) ) {
    162                 role = "subarea";
    163             } else if( p.getType().equals(OsmPrimitiveType.NODE) ) {
    164                 Node n = (Node)p;
    165                 if( !n.isIncomplete() ) {
    166                     if( n.hasKey("place") )
    167                         role = "admin_centre";
    168                     else
    169                         role = "label";
    170                 }
    171             }
    172             if( role != null )
    173                 rel.addMember(new RelationMember(role, p));
    174         }
     159    for( OsmPrimitive p : getCurrentDataSet().getSelected() ) {
     160        String role = null;
     161        if( p.getType().equals(OsmPrimitiveType.RELATION) ) {
     162        role = "subarea";
     163        } else if( p.getType().equals(OsmPrimitiveType.NODE) ) {
     164        Node n = (Node)p;
     165        if( !n.isIncomplete() ) {
     166            if( n.hasKey("place") )
     167            role = "admin_centre";
     168            else
     169            role = "label";
     170        }
     171        }
     172        if( role != null )
     173        rel.addMember(new RelationMember(role, p));
     174    }
    175175    }
    176176
     
    179179     */
    180180    private List<Command> fixWayTagsForBoundary( Relation rel ) {
    181         List<Command> commands = new ArrayList<>();
    182         if( !rel.hasKey("boundary") || !rel.hasKey("admin_level") )
    183             return commands;
    184         String adminLevelStr = rel.get("admin_level");
    185         int adminLevel = 0;
    186         try {
    187             adminLevel = Integer.parseInt(adminLevelStr);
    188         } catch( NumberFormatException e ) {
    189             return commands;
    190         }
    191         Set<OsmPrimitive> waysBoundary = new HashSet<>();
    192         Set<OsmPrimitive> waysAdminLevel = new HashSet<>();
    193         for( OsmPrimitive p : rel.getMemberPrimitives() ) {
    194             if( p instanceof Way ) {
    195                 int count = 0;
    196                 if( p.hasKey("boundary") && p.get("boundary").equals("administrative") )
    197                     count++;
    198                 if( p.hasKey("admin_level") )
    199                     count++;
    200                 if( p.keySet().size() - count == 0 ) {
    201                     if( !p.hasKey("boundary") )
    202                         waysBoundary.add(p);
    203                     if( !p.hasKey("admin_level") ) {
    204                         waysAdminLevel.add(p);
    205                     } else {
    206                         try {
    207                             int oldAdminLevel = Integer.parseInt(p.get("admin_level"));
    208                             if( oldAdminLevel > adminLevel )
    209                                 waysAdminLevel.add(p);
    210                         } catch( NumberFormatException e ) {
    211                             waysAdminLevel.add(p); // some garbage, replace it
    212                         }
    213                     }
    214                 }
    215             }
    216         }
    217         if( !waysBoundary.isEmpty() )
    218             commands.add(new ChangePropertyCommand(waysBoundary, "boundary", "administrative"));
    219         if( !waysAdminLevel.isEmpty() )
    220             commands.add(new ChangePropertyCommand(waysAdminLevel, "admin_level", adminLevelStr));
    221         return commands;
     181    List<Command> commands = new ArrayList<>();
     182    if( !rel.hasKey("boundary") || !rel.hasKey("admin_level") )
     183        return commands;
     184    String adminLevelStr = rel.get("admin_level");
     185    int adminLevel = 0;
     186    try {
     187        adminLevel = Integer.parseInt(adminLevelStr);
     188    } catch( NumberFormatException e ) {
     189        return commands;
     190    }
     191    Set<OsmPrimitive> waysBoundary = new HashSet<>();
     192    Set<OsmPrimitive> waysAdminLevel = new HashSet<>();
     193    for( OsmPrimitive p : rel.getMemberPrimitives() ) {
     194        if( p instanceof Way ) {
     195        int count = 0;
     196        if( p.hasKey("boundary") && p.get("boundary").equals("administrative") )
     197            count++;
     198        if( p.hasKey("admin_level") )
     199            count++;
     200        if( p.keySet().size() - count == 0 ) {
     201            if( !p.hasKey("boundary") )
     202            waysBoundary.add(p);
     203            if( !p.hasKey("admin_level") ) {
     204            waysAdminLevel.add(p);
     205            } else {
     206            try {
     207                int oldAdminLevel = Integer.parseInt(p.get("admin_level"));
     208                if( oldAdminLevel > adminLevel )
     209                waysAdminLevel.add(p);
     210            } catch( NumberFormatException e ) {
     211                waysAdminLevel.add(p); // some garbage, replace it
     212            }
     213            }
     214        }
     215        }
     216    }
     217    if( !waysBoundary.isEmpty() )
     218        commands.add(new ChangePropertyCommand(waysBoundary, "boundary", "administrative"));
     219    if( !waysAdminLevel.isEmpty() )
     220        commands.add(new ChangePropertyCommand(waysAdminLevel, "admin_level", adminLevelStr));
     221    return commands;
    222222    }
    223223    static public final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList(new String[] {"barrier", "source"});
    224224    private static final Set<String> REMOVE_FROM_BOUNDARY_TAGS = new TreeSet<>(Arrays.asList(new String[] {
    225                 "boundary", "boundary_type", "type", "admin_level"
    226             }));
     225        "boundary", "boundary_type", "type", "admin_level"
     226        }));
    227227
    228228    /**
     
    232232     */
    233233    private List<Command> removeTagsFromInnerWays( Relation relation ) {
    234         Map<String, String> values = new HashMap<>();
    235 
    236         if( relation.hasKeys() ) {
    237             for( String key : relation.keySet() ) {
    238                 values.put(key, relation.get(key));
    239             }
    240         }
    241 
    242         List<Way> innerWays = new ArrayList<>();
    243         List<Way> outerWays = new ArrayList<>();
    244 
    245         Set<String> conflictingKeys = new TreeSet<>();
    246 
    247         for( RelationMember m : relation.getMembers() ) {
    248 
    249             if( m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
    250                 innerWays.add(m.getWay());
    251             }
    252 
    253             if( m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
    254                 Way way = m.getWay();
    255                 outerWays.add(way);
    256                 for( String key : way.keySet() ) {
    257                     if( !values.containsKey(key) ) { //relation values take precedence
    258                         values.put(key, way.get(key));
    259                     } else if( !relation.hasKey(key) && !values.get(key).equals(way.get(key)) ) {
    260                         conflictingKeys.add(key);
    261                     }
    262                 }
    263             }
    264         }
    265 
    266         // filter out empty key conflicts - we need second iteration
    267         boolean isBoundary = getPref("boundary");
    268         if( isBoundary || !getPref("alltags") )
    269             for( RelationMember m : relation.getMembers() )
    270                 if( m.hasRole() && m.getRole().equals("outer") && m.isWay() )
    271                     for( String key : values.keySet() )
    272                         if( !m.getWay().hasKey(key) && !relation.hasKey(key) )
    273                             conflictingKeys.add(key);
    274 
    275         for( String key : conflictingKeys )
    276             values.remove(key);
    277 
    278         for( String linearTag : Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", DEFAULT_LINEAR_TAGS) )
    279             values.remove(linearTag);
    280 
    281         if( values.containsKey("natural") && values.get("natural").equals("coastline") )
    282             values.remove("natural");
    283 
    284         String name = values.get("name");
    285         if( isBoundary ) {
    286             Set<String> keySet = new TreeSet<>(values.keySet());
    287             for( String key : keySet )
    288                 if( !REMOVE_FROM_BOUNDARY_TAGS.contains(key) )
    289                     values.remove(key);
    290         }
    291 
    292         values.put("area", "yes");
    293 
    294         List<Command> commands = new ArrayList<>();
    295         boolean moveTags = getPref("tags");
    296 
    297         for( String key : values.keySet() ) {
    298             List<OsmPrimitive> affectedWays = new ArrayList<>();
    299             String value = values.get(key);
    300 
    301             for( Way way : innerWays ) {
    302                 if( way.hasKey(key) && (isBoundary || value.equals(way.get(key))) ) {
    303                     affectedWays.add(way);
    304                 }
    305             }
    306 
    307             if( moveTags ) {
    308                 // remove duplicated tags from outer ways
    309                 for( Way way : outerWays ) {
    310                     if( way.hasKey(key) ) {
    311                         affectedWays.add(way);
    312                     }
    313                 }
    314             }
    315 
    316             if( affectedWays.size() > 0 ) {
    317                 commands.add(new ChangePropertyCommand(affectedWays, key, null));
    318             }
    319         }
    320 
    321         if( moveTags ) {
    322             // add those tag values to the relation
    323             if( isBoundary )
    324                 values.put("name", name);
    325             boolean fixed = false;
    326             Relation r2 = new Relation(relation);
    327             for( String key : values.keySet() ) {
    328                 if( !r2.hasKey(key) && !key.equals("area")
    329                         && (!isBoundary || key.equals("admin_level") || key.equals("name")) ) {
    330                     if( relation.isNew() )
    331                         relation.put(key, values.get(key));
    332                     else
    333                         r2.put(key, values.get(key));
    334                     fixed = true;
    335                 }
    336             }
    337             if( fixed && !relation.isNew() )
    338                 commands.add(new ChangeCommand(relation, r2));
    339         }
    340 
    341         return commands;
     234    Map<String, String> values = new HashMap<>();
     235
     236    if( relation.hasKeys() ) {
     237        for( String key : relation.keySet() ) {
     238        values.put(key, relation.get(key));
     239        }
     240    }
     241
     242    List<Way> innerWays = new ArrayList<>();
     243    List<Way> outerWays = new ArrayList<>();
     244
     245    Set<String> conflictingKeys = new TreeSet<>();
     246
     247    for( RelationMember m : relation.getMembers() ) {
     248
     249        if( m.hasRole() && "inner".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
     250        innerWays.add(m.getWay());
     251        }
     252
     253        if( m.hasRole() && "outer".equals(m.getRole()) && m.isWay() && m.getWay().hasKeys() ) {
     254        Way way = m.getWay();
     255        outerWays.add(way);
     256        for( String key : way.keySet() ) {
     257            if( !values.containsKey(key) ) { //relation values take precedence
     258            values.put(key, way.get(key));
     259            } else if( !relation.hasKey(key) && !values.get(key).equals(way.get(key)) ) {
     260            conflictingKeys.add(key);
     261            }
     262        }
     263        }
     264    }
     265
     266    // filter out empty key conflicts - we need second iteration
     267    boolean isBoundary = getPref("boundary");
     268    if( isBoundary || !getPref("alltags") )
     269        for( RelationMember m : relation.getMembers() )
     270        if( m.hasRole() && m.getRole().equals("outer") && m.isWay() )
     271            for( String key : values.keySet() )
     272            if( !m.getWay().hasKey(key) && !relation.hasKey(key) )
     273                conflictingKeys.add(key);
     274
     275    for( String key : conflictingKeys )
     276        values.remove(key);
     277
     278    for( String linearTag : Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", DEFAULT_LINEAR_TAGS) )
     279        values.remove(linearTag);
     280
     281    if( values.containsKey("natural") && values.get("natural").equals("coastline") )
     282        values.remove("natural");
     283
     284    String name = values.get("name");
     285    if( isBoundary ) {
     286        Set<String> keySet = new TreeSet<>(values.keySet());
     287        for( String key : keySet )
     288        if( !REMOVE_FROM_BOUNDARY_TAGS.contains(key) )
     289            values.remove(key);
     290    }
     291
     292    values.put("area", "yes");
     293
     294    List<Command> commands = new ArrayList<>();
     295    boolean moveTags = getPref("tags");
     296
     297    for( String key : values.keySet() ) {
     298        List<OsmPrimitive> affectedWays = new ArrayList<>();
     299        String value = values.get(key);
     300
     301        for( Way way : innerWays ) {
     302        if( way.hasKey(key) && (isBoundary || value.equals(way.get(key))) ) {
     303            affectedWays.add(way);
     304        }
     305        }
     306
     307        if( moveTags ) {
     308        // remove duplicated tags from outer ways
     309        for( Way way : outerWays ) {
     310            if( way.hasKey(key) ) {
     311            affectedWays.add(way);
     312            }
     313        }
     314        }
     315
     316        if( affectedWays.size() > 0 ) {
     317        commands.add(new ChangePropertyCommand(affectedWays, key, null));
     318        }
     319    }
     320
     321    if( moveTags ) {
     322        // add those tag values to the relation
     323        if( isBoundary )
     324        values.put("name", name);
     325        boolean fixed = false;
     326        Relation r2 = new Relation(relation);
     327        for( String key : values.keySet() ) {
     328        if( !r2.hasKey(key) && !key.equals("area")
     329            && (!isBoundary || key.equals("admin_level") || key.equals("name")) ) {
     330            if( relation.isNew() )
     331            relation.put(key, values.get(key));
     332            else
     333            r2.put(key, values.get(key));
     334            fixed = true;
     335        }
     336        }
     337        if( fixed && !relation.isNew() )
     338        commands.add(new ChangeCommand(relation, r2));
     339    }
     340
     341    return commands;
    342342    }
    343343
     
    348348     */
    349349    private boolean askForAdminLevelAndName( Relation rel ) {
    350         String relAL = rel.get("admin_level");
    351         String relName = rel.get("name");
    352         if( relAL != null && relName != null )
    353             return true;
    354 
    355         JPanel panel = new JPanel(new GridBagLayout());
    356         panel.add(new JLabel(tr("Enter admin level and name for the border relation:")), GBC.eol().insets(0, 0, 0, 5));
    357 
    358         final JTextField admin = new JTextField();
    359         admin.setText(relAL != null ? relAL : Main.pref.get(PREF_MULTIPOLY + "lastadmin", ""));
    360         panel.add(new JLabel(tr("Admin level")), GBC.std());
    361         panel.add(Box.createHorizontalStrut(10), GBC.std());
    362         panel.add(admin, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 5));
    363 
    364         final JTextField name = new JTextField();
    365         if( relName != null )
    366             name.setText(relName);
    367         panel.add(new JLabel(tr("Name")), GBC.std());
    368         panel.add(Box.createHorizontalStrut(10), GBC.std());
    369         panel.add(name, GBC.eol().fill(GBC.HORIZONTAL));
    370 
    371         final JOptionPane optionPane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
    372             @Override
    373             public void selectInitialValue() {
    374                 admin.requestFocusInWindow();
    375                 admin.selectAll();
    376             }
    377         };
    378         final JDialog dlg = optionPane.createDialog(Main.parent, tr("Create a new relation"));
    379         dlg.setModalityType(ModalityType.DOCUMENT_MODAL);
    380 
    381         name.addActionListener(new ActionListener() {
    382             public void actionPerformed( ActionEvent e ) {
    383                 dlg.setVisible(false);
    384                 optionPane.setValue(JOptionPane.OK_OPTION);
    385             }
    386         });
    387 
    388         dlg.setVisible(true);
    389 
    390         Object answer = optionPane.getValue();
    391         if( answer == null || answer == JOptionPane.UNINITIALIZED_VALUE
    392                 || (answer instanceof Integer && (Integer)answer != JOptionPane.OK_OPTION) ) {
    393             return false;
    394         }
    395 
    396         String admin_level = admin.getText().trim();
    397         String new_name = name.getText().trim();
    398         if( admin_level.equals("10") || (admin_level.length() == 1 && Character.isDigit(admin_level.charAt(0))) ) {
    399             rel.put("admin_level", admin_level);
    400             Main.pref.put(PREF_MULTIPOLY + "lastadmin", admin_level);
    401         }
    402         if( new_name.length() > 0 )
    403             rel.put("name", new_name);
    404         return true;
     350    String relAL = rel.get("admin_level");
     351    String relName = rel.get("name");
     352    if( relAL != null && relName != null )
     353        return true;
     354
     355    JPanel panel = new JPanel(new GridBagLayout());
     356    panel.add(new JLabel(tr("Enter admin level and name for the border relation:")), GBC.eol().insets(0, 0, 0, 5));
     357
     358    final JTextField admin = new JTextField();
     359    admin.setText(relAL != null ? relAL : Main.pref.get(PREF_MULTIPOLY + "lastadmin", ""));
     360    panel.add(new JLabel(tr("Admin level")), GBC.std());
     361    panel.add(Box.createHorizontalStrut(10), GBC.std());
     362    panel.add(admin, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 5));
     363
     364    final JTextField name = new JTextField();
     365    if( relName != null )
     366        name.setText(relName);
     367    panel.add(new JLabel(tr("Name")), GBC.std());
     368    panel.add(Box.createHorizontalStrut(10), GBC.std());
     369    panel.add(name, GBC.eol().fill(GBC.HORIZONTAL));
     370
     371    final JOptionPane optionPane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION) {
     372        @Override
     373        public void selectInitialValue() {
     374        admin.requestFocusInWindow();
     375        admin.selectAll();
     376        }
     377    };
     378    final JDialog dlg = optionPane.createDialog(Main.parent, tr("Create a new relation"));
     379    dlg.setModalityType(ModalityType.DOCUMENT_MODAL);
     380
     381    name.addActionListener(new ActionListener() {
     382        public void actionPerformed( ActionEvent e ) {
     383        dlg.setVisible(false);
     384        optionPane.setValue(JOptionPane.OK_OPTION);
     385        }
     386    });
     387
     388    dlg.setVisible(true);
     389
     390    Object answer = optionPane.getValue();
     391    if( answer == null || answer == JOptionPane.UNINITIALIZED_VALUE
     392        || (answer instanceof Integer && (Integer)answer != JOptionPane.OK_OPTION) ) {
     393        return false;
     394    }
     395
     396    String admin_level = admin.getText().trim();
     397    String new_name = name.getText().trim();
     398    if( admin_level.equals("10") || (admin_level.length() == 1 && Character.isDigit(admin_level.charAt(0))) ) {
     399        rel.put("admin_level", admin_level);
     400        Main.pref.put(PREF_MULTIPOLY + "lastadmin", admin_level);
     401    }
     402    if( new_name.length() > 0 )
     403        rel.put("name", new_name);
     404    return true;
    405405    }
    406406}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/ReconstructPolygonAction.java

    r30737 r30738  
    4242   
    4343    private static final List<String> IRRELEVANT_KEYS = Arrays.asList(new String[] {
    44         "source", "created_by", "note"});
     44    "source", "created_by", "note"});
    4545
    4646    public ReconstructPolygonAction( ChosenRelation rel ) {
    4747        super(tr("Reconstruct polygon"));
    4848        putValue(SMALL_ICON, ImageProvider.get("dialogs", "filter"));
    49         putValue(LONG_DESCRIPTION, "Reconstruct polygon from multipolygon relation");
     49    putValue(LONG_DESCRIPTION, "Reconstruct polygon from multipolygon relation");
    5050        this.rel = rel;
    5151        rel.addChosenRelationListener(this);
     
    5555    public void actionPerformed( ActionEvent e ) {
    5656        Relation r = rel.get();
    57         List<Way> ways = new ArrayList<>();
    58         boolean wont = false;
    59         for( RelationMember m : r.getMembers() ) {
    60             if( m.isWay() )
    61                 ways.add(m.getWay());
    62             else
    63                 wont = true;
    64         }
    65         if( wont ) {
    66             JOptionPane.showMessageDialog(Main.parent, tr("Multipolygon must consist only of ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
    67             return;
    68         }
    69        
    70         MultipolygonBuilder mpc = new MultipolygonBuilder();
    71         String error = mpc.makeFromWays(ways);
    72         if( error != null ) {
    73             JOptionPane.showMessageDialog(Main.parent, error);
    74             return;
    75         }
    76        
    77         if( !mpc.innerWays.isEmpty() ) {
    78             JOptionPane.showMessageDialog(Main.parent, tr("Reconstruction of polygons can be done only from outer ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
    79             return;
    80         }
    81        
    82         rel.clear();
    83         List<Way> newSelection = new ArrayList<>();
    84         List<Command> commands = new ArrayList<>();
     57    List<Way> ways = new ArrayList<>();
     58    boolean wont = false;
     59    for( RelationMember m : r.getMembers() ) {
     60        if( m.isWay() )
     61        ways.add(m.getWay());
     62        else
     63        wont = true;
     64    }
     65    if( wont ) {
     66        JOptionPane.showMessageDialog(Main.parent, tr("Multipolygon must consist only of ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
     67        return;
     68    }
     69   
     70    MultipolygonBuilder mpc = new MultipolygonBuilder();
     71    String error = mpc.makeFromWays(ways);
     72    if( error != null ) {
     73        JOptionPane.showMessageDialog(Main.parent, error);
     74        return;
     75    }
     76   
     77    if( !mpc.innerWays.isEmpty() ) {
     78        JOptionPane.showMessageDialog(Main.parent, tr("Reconstruction of polygons can be done only from outer ways"), tr("Reconstruct polygon"), JOptionPane.ERROR_MESSAGE);
     79        return;
     80    }
     81   
     82    rel.clear();
     83    List<Way> newSelection = new ArrayList<>();
     84    List<Command> commands = new ArrayList<>();
    8585        Command c = DeleteCommand.delete(Main.main.getEditLayer(), Collections.singleton(r), true, true);
    8686        if( c == null )
    8787            return;
    88         commands.add(c);
    89        
    90         for( JoinedPolygon p : mpc.outerWays ) {
    91             // move all tags from relation and common tags from ways
    92             Map<String, String> tags = p.ways.get(0).getKeys();
    93             List<OsmPrimitive> relations = p.ways.get(0).getReferrers();
    94             Set<String> noTags = new HashSet<>(r.keySet());
    95             for( int i = 1; i < p.ways.size(); i++ ) {
    96                 Way w = p.ways.get(i);
    97                 for( String key : w.keySet() ) {
    98                     String value = w.get(key);
    99                     if( !noTags.contains(key) && tags.containsKey(key) && !tags.get(key).equals(value) ) {
    100                         tags.remove(key);
    101                         noTags.add(key);
    102                     }
    103                 }
    104                 List<OsmPrimitive> referrers = w.getReferrers();
    105                 for( Iterator<OsmPrimitive> ref1 = relations.iterator(); ref1.hasNext(); )
    106                     if( !referrers.contains(ref1.next()) )
    107                         ref1.remove();
    108             }
    109             tags.putAll(r.getKeys());
    110             tags.remove("type");
    111            
    112             // then delete ways that are not relevant (do not take part in other relations of have strange tags)
    113             Way candidateWay = null;
    114             for( Way w : p.ways ) {
    115                 if( w.getReferrers().equals(relations) ) {
    116                     // check tags that remain
    117                     Set<String> keys = new HashSet<>(w.keySet());
    118                     keys.removeAll(tags.keySet());
    119                     keys.removeAll(IRRELEVANT_KEYS);
    120                     if( keys.isEmpty() ) {
    121                         if( candidateWay == null )
    122                             candidateWay = w;
    123                         else {
    124                             if( candidateWay.isNew() && !w.isNew() ) {
    125                                 // prefer ways that are already in the database
    126                                 Way tmp = w;
    127                                 w = candidateWay;
    128                                 candidateWay = tmp;
    129                             }
    130                             commands.add(new DeleteCommand(w));
    131                         }
    132                     }
    133                 }
    134             }
    135            
    136             // take the first way, put all nodes into it, making it a closed polygon
    137             Way result = candidateWay == null ? new Way() : new Way(candidateWay);
    138             result.setNodes(p.nodes);
    139             result.addNode(result.firstNode());
    140             result.setKeys(tags);
    141             newSelection.add(candidateWay == null ? result : candidateWay);
    142             commands.add(candidateWay == null ? new AddCommand(result) : new ChangeCommand(candidateWay, result));
    143         }
    144        
     88    commands.add(c);
     89   
     90    for( JoinedPolygon p : mpc.outerWays ) {
     91        // move all tags from relation and common tags from ways
     92        Map<String, String> tags = p.ways.get(0).getKeys();
     93        List<OsmPrimitive> relations = p.ways.get(0).getReferrers();
     94        Set<String> noTags = new HashSet<>(r.keySet());
     95        for( int i = 1; i < p.ways.size(); i++ ) {
     96        Way w = p.ways.get(i);
     97        for( String key : w.keySet() ) {
     98            String value = w.get(key);
     99            if( !noTags.contains(key) && tags.containsKey(key) && !tags.get(key).equals(value) ) {
     100            tags.remove(key);
     101            noTags.add(key);
     102            }
     103        }
     104        List<OsmPrimitive> referrers = w.getReferrers();
     105        for( Iterator<OsmPrimitive> ref1 = relations.iterator(); ref1.hasNext(); )
     106            if( !referrers.contains(ref1.next()) )
     107            ref1.remove();
     108        }
     109        tags.putAll(r.getKeys());
     110        tags.remove("type");
     111       
     112        // then delete ways that are not relevant (do not take part in other relations of have strange tags)
     113        Way candidateWay = null;
     114        for( Way w : p.ways ) {
     115        if( w.getReferrers().equals(relations) ) {
     116            // check tags that remain
     117            Set<String> keys = new HashSet<>(w.keySet());
     118            keys.removeAll(tags.keySet());
     119            keys.removeAll(IRRELEVANT_KEYS);
     120            if( keys.isEmpty() ) {
     121            if( candidateWay == null )
     122                candidateWay = w;
     123            else {
     124                if( candidateWay.isNew() && !w.isNew() ) {
     125                // prefer ways that are already in the database
     126                Way tmp = w;
     127                w = candidateWay;
     128                candidateWay = tmp;
     129                }
     130                commands.add(new DeleteCommand(w));
     131            }
     132            }
     133        }
     134        }
     135       
     136        // take the first way, put all nodes into it, making it a closed polygon
     137        Way result = candidateWay == null ? new Way() : new Way(candidateWay);
     138        result.setNodes(p.nodes);
     139        result.addNode(result.firstNode());
     140        result.setKeys(tags);
     141        newSelection.add(candidateWay == null ? result : candidateWay);
     142        commands.add(candidateWay == null ? new AddCommand(result) : new ChangeCommand(candidateWay, result));
     143    }
     144   
    145145        Main.main.undoRedo.add(new SequenceCommand(tr("Reconstruct polygons from relation {0}",
    146                 r.getDisplayName(DefaultNameFormatter.getInstance())), commands));
    147         Main.main.getCurrentDataSet().setSelected(newSelection);
     146        r.getDisplayName(DefaultNameFormatter.getInstance())), commands));
     147    Main.main.getCurrentDataSet().setSelected(newSelection);
    148148    }
    149149
    150150    public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) {
    151         setEnabled(isSuitableRelation(newRelation));
     151    setEnabled(isSuitableRelation(newRelation));
    152152    }
    153153   
    154154    private boolean isSuitableRelation( Relation newRelation ) {
    155         if( newRelation == null || !"multipolygon".equals(newRelation.get("type")) || newRelation.getMembersCount() == 0 )
    156             return false;
    157         else {
    158             for( RelationMember m : newRelation.getMembers() )
    159                 if( "inner".equals(m.getRole()) )
    160                     return false;
    161             return true;
    162         }
     155    if( newRelation == null || !"multipolygon".equals(newRelation.get("type")) || newRelation.getMembersCount() == 0 )
     156        return false;
     157    else {
     158        for( RelationMember m : newRelation.getMembers() )
     159        if( "inner".equals(m.getRole()) )
     160            return false;
     161        return true;
     162    }
    163163    }
    164164}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SortAndFixAction.java

    r30737 r30738  
    2525
    2626public class SortAndFixAction extends AbstractAction implements ChosenRelationListener {
    27         private static final long serialVersionUID = 1L;
    28         private ChosenRelation rel;
     27    private static final long serialVersionUID = 1L;
     28    private ChosenRelation rel;
    2929    private List<RelationFixer> fixers;
    3030
     
    6767
    6868    private RelationFixer getFixer( Relation rel ) {
    69         for(RelationFixer fixer : fixers)
    70                 if (fixer.isFixerApplicable(rel))
    71                         return fixer;
    72         return new NothingFixer();
     69        for(RelationFixer fixer : fixers)
     70            if (fixer.isFixerApplicable(rel))
     71                return fixer;
     72        return new NothingFixer();
    7373    }
    7474
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SplittingMultipolygons.java

    r30737 r30738  
    2424
    2525    public static boolean canProcess( Collection<Way> ways ) {
    26         List<Way> rings = new ArrayList<>();
    27         List<Way> arcs = new ArrayList<>();
    28         Area a = Main.main.getCurrentDataSet().getDataSourceArea();
    29         for( Way way : ways ) {
    30             if( way.isDeleted() )
    31                 return false;
    32             for( Node n : way.getNodes() ) {
    33                 LatLon ll = n.getCoor();
    34                 if( n.isIncomplete() || (a != null && !a.contains(ll.getX(), ll.getY())) )
    35                     return false;
    36             }
    37             if( way.isClosed() )
    38                 rings.add(way);
    39             else
    40                 arcs.add(way);
    41         }
    42        
    43         // If there are more that one segment, check that they touch rings
    44         if( arcs.size() > 1 ) {
    45             for( Way segment : arcs ) {
    46                 boolean found = false;
    47                 for( Way ring : rings )
    48                     if( ring.containsNode(segment.firstNode()) && ring.containsNode(segment.lastNode()) )
    49                         found = true;
    50                 if( !found )
    51                     return false;
    52             }
    53         }
    54 
    55         if( rings.isEmpty() && arcs.isEmpty() )
    56             return false;
    57 
    58         // check for non-containment of rings
    59         for( int i = 0; i < rings.size() - 1; i++ ) {
    60             for( int j = i + 1; j < rings.size(); j++ ) {
    61                 PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
    62                 if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
    63                     return false;
    64             }
    65         }
    66 
    67         return true;
     26    List<Way> rings = new ArrayList<>();
     27    List<Way> arcs = new ArrayList<>();
     28    Area a = Main.main.getCurrentDataSet().getDataSourceArea();
     29    for( Way way : ways ) {
     30        if( way.isDeleted() )
     31        return false;
     32        for( Node n : way.getNodes() ) {
     33            LatLon ll = n.getCoor();
     34            if( n.isIncomplete() || (a != null && !a.contains(ll.getX(), ll.getY())) )
     35                return false;
     36        }
     37        if( way.isClosed() )
     38        rings.add(way);
     39        else
     40        arcs.add(way);
     41    }
     42   
     43    // If there are more that one segment, check that they touch rings
     44    if( arcs.size() > 1 ) {
     45        for( Way segment : arcs ) {
     46        boolean found = false;
     47        for( Way ring : rings )
     48            if( ring.containsNode(segment.firstNode()) && ring.containsNode(segment.lastNode()) )
     49            found = true;
     50        if( !found )
     51            return false;
     52        }
     53    }
     54
     55    if( rings.isEmpty() && arcs.isEmpty() )
     56        return false;
     57
     58    // check for non-containment of rings
     59    for( int i = 0; i < rings.size() - 1; i++ ) {
     60        for( int j = i + 1; j < rings.size(); j++ ) {
     61        PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
     62        if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
     63            return false;
     64        }
     65    }
     66
     67    return true;
    6868    }
    6969   
    7070    public static List<Relation> process( Collection<Way> selectedWays ) {
    71 //      System.out.println("---------------------------------------");
    72         List<Relation> result = new ArrayList<>();
    73         List<Way> rings = new ArrayList<>();
    74         List<Way> arcs = new ArrayList<>();
    75         for( Way way : selectedWays ) {
    76             if( way.isClosed() )
    77                 rings.add(way);
    78             else
    79                 arcs.add(way);
    80         }
    81 
    82         for( Way ring : rings ) {
    83             List<Command> commands = new ArrayList<>();
    84             Relation newRelation = SplittingMultipolygons.attachRingToNeighbours(ring, commands);
    85             if( newRelation != null && !commands.isEmpty() ) {
    86                 Main.main.undoRedo.add(commands.get(0));
    87                 result.add(newRelation);
    88             }
    89         }
    90 
    91         for( Way arc : arcs) {
    92             List<Command> commands = new ArrayList<>();
    93             Relation newRelation = SplittingMultipolygons.tryToCloseOneWay(arc, commands);
    94             if( newRelation != null && !commands.isEmpty() ) {
    95                 Main.main.undoRedo.add(commands.get(0));
    96                 result.add(newRelation);
    97             }
    98         }
    99         return result;
     71//    System.out.println("---------------------------------------");
     72    List<Relation> result = new ArrayList<>();
     73    List<Way> rings = new ArrayList<>();
     74    List<Way> arcs = new ArrayList<>();
     75    for( Way way : selectedWays ) {
     76        if( way.isClosed() )
     77        rings.add(way);
     78        else
     79        arcs.add(way);
     80    }
     81
     82    for( Way ring : rings ) {
     83        List<Command> commands = new ArrayList<>();
     84        Relation newRelation = SplittingMultipolygons.attachRingToNeighbours(ring, commands);
     85        if( newRelation != null && !commands.isEmpty() ) {
     86        Main.main.undoRedo.add(commands.get(0));
     87        result.add(newRelation);
     88        }
     89    }
     90
     91    for( Way arc : arcs) {
     92        List<Command> commands = new ArrayList<>();
     93        Relation newRelation = SplittingMultipolygons.tryToCloseOneWay(arc, commands);
     94        if( newRelation != null && !commands.isEmpty() ) {
     95        Main.main.undoRedo.add(commands.get(0));
     96        result.add(newRelation);
     97        }
     98    }
     99    return result;
    100100    }
    101101
     
    104104     */
    105105    private static void closePolygon( List<Node> base, List<Node> append ) {
    106         if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
    107             List<Node> ap2 = new ArrayList<>(append);
    108             Collections.reverse(ap2);
    109             append = ap2;
    110         }
    111         base.remove(base.size() - 1);
    112         base.addAll(append);
     106    if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
     107        List<Node> ap2 = new ArrayList<>(append);
     108        Collections.reverse(ap2);
     109        append = ap2;
     110    }
     111    base.remove(base.size() - 1);
     112    base.addAll(append);
    113113    }
    114114
     
    117117     */
    118118    private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) {
    119         EastNorth en1 = n1.getEastNorth();
    120         EastNorth en2 = n2.getEastNorth();
    121         Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
    122         return Geometry.nodeInsidePolygon(testNode, polygon);
     119    EastNorth en1 = n1.getEastNorth();
     120    EastNorth en2 = n2.getEastNorth();
     121    Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
     122    return Geometry.nodeInsidePolygon(testNode, polygon);
    123123    }
    124124
     
    131131     */
    132132    public static List<Way> splitWay( Way w, Node n1, Node n2, List<Command> commands ) {
    133         List<Node> nodes = new ArrayList<>(w.getNodes());
    134         if( w.isClosed() )
    135             nodes.remove(nodes.size() - 1);
    136         int index1 = nodes.indexOf(n1);
    137         int index2 = n2 == null ? -1 : nodes.indexOf(n2);
    138         if( index1 > index2 ) {
    139             int tmp = index1;
    140             index1 = index2;
    141             index2 = tmp;
    142         }
    143         // right now index2 >= index1
    144         if( index2 < 1 || index1 >= w.getNodesCount() - 1 || index2 >= w.getNodesCount() )
    145             return Collections.emptyList();
    146         if( w.isClosed() && (index1 < 0 || index1 == index2 || index1 + w.getNodesCount() == index2) )
    147             return Collections.emptyList();
    148        
    149         // todo: download parent relations!
    150 
    151         // make a list of segments
    152         List<List<Node>> chunks = new ArrayList<>(2);
    153         List<Node> chunk = new ArrayList<>();
    154         for( int i = 0; i < nodes.size(); i++ ) {
    155             chunk.add(nodes.get(i));
    156             if( (w.isClosed() || chunk.size() > 1) && (i == index1 || i == index2) ) {
    157                 chunks.add(chunk);
    158                 chunk = new ArrayList<>();
    159                 chunk.add(nodes.get(i));
    160             }
    161         }
    162         chunks.add(chunk);
    163 
    164         // for closed way ignore the way boundary
    165         if( w.isClosed() ) {
    166             chunks.get(chunks.size() - 1).addAll(chunks.get(0));
    167             chunks.remove(0);
    168         } else if( chunks.get(chunks.size() - 1).size() < 2 )
    169             chunks.remove(chunks.size() - 1);
    170 
    171         // todo remove debug: show chunks array contents
    172         /*for( List<Node> c1 : chunks ) {
    173         for( Node cn1 : c1 )
    174         System.out.print(cn1.getId() + ",");
    175         System.out.println();
    176         }*/
    177 
    178         // build a map of referencing relations
    179         Map<Relation, Integer> references = new HashMap<>();
    180         List<Command> relationCommands = new ArrayList<>();
    181         for( OsmPrimitive p : w.getReferrers() ) {
    182             if( p instanceof Relation ) {
    183                 Relation rel = commands == null ? (Relation)p : new Relation((Relation)p);
    184                 if( commands != null )
    185                     relationCommands.add(new ChangeCommand((Relation)p, rel));
    186                 for( int i = 0; i < rel.getMembersCount(); i++ )
    187                     if( rel.getMember(i).getMember().equals(w) )
    188                         references.put(rel, Integer.valueOf(i));
    189             }
    190         }
    191 
    192         // build ways
    193         List<Way> result = new ArrayList<>();
    194         Way updatedWay = commands == null ? w : new Way(w);
    195         updatedWay.setNodes(chunks.get(0));
    196         if( commands != null ) {
    197             commands.add(new ChangeCommand(w, updatedWay));
    198             result.add(updatedWay);
    199         }
    200 
    201         for( int i = 1; i < chunks.size(); i++ ) {
    202             List<Node> achunk = chunks.get(i);
    203             Way newWay = new Way();
    204             newWay.setKeys(w.getKeys());
    205             result.add(newWay);
    206             for( Relation rel : references.keySet() ) {
    207                 int relIndex = references.get(rel);
    208                 rel.addMember(relIndex + 1, new RelationMember(rel.getMember(relIndex).getRole(), newWay));
    209             }
    210             newWay.setNodes(achunk);
    211             if( commands != null )
    212                 commands.add(new AddCommand(newWay));
    213         }
    214         if( commands != null )
    215             commands.addAll(relationCommands);
    216         return result;
     133    List<Node> nodes = new ArrayList<>(w.getNodes());
     134    if( w.isClosed() )
     135        nodes.remove(nodes.size() - 1);
     136    int index1 = nodes.indexOf(n1);
     137    int index2 = n2 == null ? -1 : nodes.indexOf(n2);
     138    if( index1 > index2 ) {
     139        int tmp = index1;
     140        index1 = index2;
     141        index2 = tmp;
     142    }
     143    // right now index2 >= index1
     144    if( index2 < 1 || index1 >= w.getNodesCount() - 1 || index2 >= w.getNodesCount() )
     145        return Collections.emptyList();
     146    if( w.isClosed() && (index1 < 0 || index1 == index2 || index1 + w.getNodesCount() == index2) )
     147        return Collections.emptyList();
     148   
     149    // todo: download parent relations!
     150
     151    // make a list of segments
     152    List<List<Node>> chunks = new ArrayList<>(2);
     153    List<Node> chunk = new ArrayList<>();
     154    for( int i = 0; i < nodes.size(); i++ ) {
     155        chunk.add(nodes.get(i));
     156        if( (w.isClosed() || chunk.size() > 1) && (i == index1 || i == index2) ) {
     157        chunks.add(chunk);
     158        chunk = new ArrayList<>();
     159        chunk.add(nodes.get(i));
     160        }
     161    }
     162    chunks.add(chunk);
     163
     164    // for closed way ignore the way boundary
     165    if( w.isClosed() ) {
     166        chunks.get(chunks.size() - 1).addAll(chunks.get(0));
     167        chunks.remove(0);
     168    } else if( chunks.get(chunks.size() - 1).size() < 2 )
     169        chunks.remove(chunks.size() - 1);
     170
     171    // todo remove debug: show chunks array contents
     172    /*for( List<Node> c1 : chunks ) {
     173    for( Node cn1 : c1 )
     174    System.out.print(cn1.getId() + ",");
     175    System.out.println();
     176    }*/
     177
     178    // build a map of referencing relations
     179    Map<Relation, Integer> references = new HashMap<>();
     180    List<Command> relationCommands = new ArrayList<>();
     181    for( OsmPrimitive p : w.getReferrers() ) {
     182        if( p instanceof Relation ) {
     183        Relation rel = commands == null ? (Relation)p : new Relation((Relation)p);
     184        if( commands != null )
     185            relationCommands.add(new ChangeCommand((Relation)p, rel));
     186        for( int i = 0; i < rel.getMembersCount(); i++ )
     187            if( rel.getMember(i).getMember().equals(w) )
     188            references.put(rel, Integer.valueOf(i));
     189        }
     190    }
     191
     192    // build ways
     193    List<Way> result = new ArrayList<>();
     194    Way updatedWay = commands == null ? w : new Way(w);
     195    updatedWay.setNodes(chunks.get(0));
     196    if( commands != null ) {
     197        commands.add(new ChangeCommand(w, updatedWay));
     198        result.add(updatedWay);
     199    }
     200
     201    for( int i = 1; i < chunks.size(); i++ ) {
     202        List<Node> achunk = chunks.get(i);
     203        Way newWay = new Way();
     204        newWay.setKeys(w.getKeys());
     205        result.add(newWay);
     206        for( Relation rel : references.keySet() ) {
     207        int relIndex = references.get(rel);
     208        rel.addMember(relIndex + 1, new RelationMember(rel.getMember(relIndex).getRole(), newWay));
     209        }
     210        newWay.setNodes(achunk);
     211        if( commands != null )
     212        commands.add(new AddCommand(newWay));
     213    }
     214    if( commands != null )
     215        commands.addAll(relationCommands);
     216    return result;
    217217    }
    218218
    219219    public static List<Way> splitWay( Way w, Node n1, Node n2 ) {
    220         return splitWay(w, n1, n2, null);
     220    return splitWay(w, n1, n2, null);
    221221    }
    222222
     
    225225     */
    226226    public static Relation tryToCloseOneWay( Way segment, List<Command> resultingCommands ) {
    227         if( segment.isClosed() || segment.isIncomplete() )
    228             return null;
    229 
    230         List<Way> ways = intersection(
    231                 OsmPrimitive.getFilteredList(segment.firstNode().getReferrers(), Way.class),
    232                 OsmPrimitive.getFilteredList(segment.lastNode().getReferrers(), Way.class));
    233         ways.remove(segment);
    234         for( Iterator<Way> iter = ways.iterator(); iter.hasNext(); ) {
    235             boolean save = false;
    236             for( OsmPrimitive ref : iter.next().getReferrers() )
    237                 if( ref instanceof Relation && ((Relation)ref).isMultipolygon() && !ref.isDeleted() )
    238                     save = true;
    239             if( !save )
    240                 iter.remove();
    241         }
    242         if( ways.isEmpty() )
    243             return null; // well...
    244         Way target = ways.get(0);
    245 
    246         // time to create a new multipolygon relation and a command stack
    247         List<Command> commands = new ArrayList<>();
    248         Relation newRelation = new Relation();
    249         newRelation.put("type", "multipolygon");
    250         newRelation.addMember(new RelationMember("outer", segment));
    251         Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
    252         Way segmentCopy = new Way(segment);
    253         boolean changed = false;
    254         for( String key : segmentCopy.keySet() ) {
    255             if( !linearTags.contains(key) ) {
    256                 newRelation.put(key, segmentCopy.get(key));
    257                 segmentCopy.remove(key);
    258                 changed = true;
    259             }
    260         }
    261         if( changed )
    262             commands.add(new ChangeCommand(segment, segmentCopy));
    263 
    264         // now split the way, at last
    265         List<Way> newWays = new ArrayList<>(splitWay(target, segment.firstNode(), segment.lastNode(), commands));
    266 
    267         Way addingWay = null;
    268         if( target.isClosed() ) {
    269             Way utarget = newWays.get(1);
    270             Way alternate = newWays.get(0);
    271             List<Node> testRing = new ArrayList<>(segment.getNodes());
    272             closePolygon(testRing, utarget.getNodes());
    273             addingWay = segmentInsidePolygon(alternate.getNode(0), alternate.getNode(1), testRing) ? alternate : utarget;
    274         } else {
    275             for( Way w : newWays ) {
    276                 if( (w.firstNode().equals(segment.firstNode()) && w.lastNode().equals(segment.lastNode()))
    277                         || (w.firstNode().equals(segment.lastNode()) && w.lastNode().equals(segment.firstNode())) ) {
    278                     addingWay = w;
    279                     break;
    280                 }
    281             }
    282         }
    283         newRelation.addMember(new RelationMember("outer", addingWay.getUniqueId() == target.getUniqueId() ? target : addingWay));
    284         commands.add(new AddCommand(newRelation));
    285         resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
    286                 DefaultNameFormatter.getInstance().format(segment)), commands));
    287         return newRelation;
     227    if( segment.isClosed() || segment.isIncomplete() )
     228        return null;
     229
     230    List<Way> ways = intersection(
     231        OsmPrimitive.getFilteredList(segment.firstNode().getReferrers(), Way.class),
     232        OsmPrimitive.getFilteredList(segment.lastNode().getReferrers(), Way.class));
     233    ways.remove(segment);
     234    for( Iterator<Way> iter = ways.iterator(); iter.hasNext(); ) {
     235        boolean save = false;
     236        for( OsmPrimitive ref : iter.next().getReferrers() )
     237        if( ref instanceof Relation && ((Relation)ref).isMultipolygon() && !ref.isDeleted() )
     238            save = true;
     239        if( !save )
     240        iter.remove();
     241    }
     242    if( ways.isEmpty() )
     243        return null; // well...
     244    Way target = ways.get(0);
     245
     246    // time to create a new multipolygon relation and a command stack
     247    List<Command> commands = new ArrayList<>();
     248    Relation newRelation = new Relation();
     249    newRelation.put("type", "multipolygon");
     250    newRelation.addMember(new RelationMember("outer", segment));
     251    Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
     252    Way segmentCopy = new Way(segment);
     253    boolean changed = false;
     254    for( String key : segmentCopy.keySet() ) {
     255        if( !linearTags.contains(key) ) {
     256        newRelation.put(key, segmentCopy.get(key));
     257        segmentCopy.remove(key);
     258        changed = true;
     259        }
     260    }
     261    if( changed )
     262        commands.add(new ChangeCommand(segment, segmentCopy));
     263
     264    // now split the way, at last
     265    List<Way> newWays = new ArrayList<>(splitWay(target, segment.firstNode(), segment.lastNode(), commands));
     266
     267    Way addingWay = null;
     268    if( target.isClosed() ) {
     269        Way utarget = newWays.get(1);
     270        Way alternate = newWays.get(0);
     271        List<Node> testRing = new ArrayList<>(segment.getNodes());
     272        closePolygon(testRing, utarget.getNodes());
     273        addingWay = segmentInsidePolygon(alternate.getNode(0), alternate.getNode(1), testRing) ? alternate : utarget;
     274    } else {
     275        for( Way w : newWays ) {
     276        if( (w.firstNode().equals(segment.firstNode()) && w.lastNode().equals(segment.lastNode()))
     277            || (w.firstNode().equals(segment.lastNode()) && w.lastNode().equals(segment.firstNode())) ) {
     278            addingWay = w;
     279            break;
     280        }
     281        }
     282    }
     283    newRelation.addMember(new RelationMember("outer", addingWay.getUniqueId() == target.getUniqueId() ? target : addingWay));
     284    commands.add(new AddCommand(newRelation));
     285    resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
     286        DefaultNameFormatter.getInstance().format(segment)), commands));
     287    return newRelation;
    288288    }
    289289
     
    292292     */
    293293    private static <T> List<T> intersection( Collection<T> list1, Collection<T> list2 ) {
    294         List<T> result = new ArrayList<>();
    295         for( T item : list1 )
    296             if( list2.contains(item) )
    297                 result.add(item);
    298         return result;
     294    List<T> result = new ArrayList<>();
     295    for( T item : list1 )
     296        if( list2.contains(item) )
     297        result.add(item);
     298    return result;
    299299    }
    300300   
     
    303303     */
    304304    public static Relation attachRingToNeighbours( Way ring, List<Command> resultingCommands ) {
    305         if( !ring.isClosed() || ring.isIncomplete() )
    306             return null;
    307         Map<Way, Boolean> touchingWays = new HashMap<>();
    308         for( Node n : ring.getNodes() ) {
    309             for( OsmPrimitive p : n.getReferrers() ) {
    310                 if( p instanceof Way && !p.equals(ring) ) {
    311                     for( OsmPrimitive r : p.getReferrers() ) {
    312                         if( r instanceof Relation && ((Relation)r).hasKey("type") && ((Relation)r).get("type").equals("multipolygon") ) {
    313                             if( touchingWays.containsKey((Way)p) )
    314                                 touchingWays.put((Way)p, Boolean.TRUE);
    315                             else
    316                                 touchingWays.put((Way)p, Boolean.FALSE);
    317                             break;
    318                         }
    319                     }
    320                 }
    321             }
    322         }
    323        
    324         List<TheRing> otherWays = new ArrayList<>();
    325         for( Way w : touchingWays.keySet() )
    326             if( touchingWays.get(w) ) {
    327                 otherWays.add(new TheRing(w));
    328 //              System.out.println("Touching ring: " + otherWays.get(otherWays.size()-1));
    329             }
    330        
    331 //      for( Iterator<Way> keys = touchingWays.keySet().iterator(); keys.hasNext(); ) {
    332 //          if( !touchingWays.get(keys.next()) )
    333 //              keys.remove();
    334 //      }
    335        
    336         // now touchingWays has only ways that touch the ring twice
    337         List<Command> commands = new ArrayList<>();
    338         TheRing theRing = new TheRing(ring); // this is actually useful
    339        
    340         for( TheRing otherRing : otherWays )
    341             theRing.collide(otherRing);
    342        
    343         theRing.putSourceWayFirst();
    344         for( TheRing otherRing : otherWays )
    345             otherRing.putSourceWayFirst();
    346        
    347         Map<Relation, Relation> relationCache = new HashMap<>();
    348         for( TheRing otherRing : otherWays )
    349             commands.addAll(otherRing.getCommands(false, relationCache));
    350         commands.addAll(theRing.getCommands(relationCache));
    351         TheRing.updateCommandsWithRelations(commands, relationCache);
    352         resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
    353                 DefaultNameFormatter.getInstance().format(ring)), commands));
    354         return theRing.getRelation();
     305    if( !ring.isClosed() || ring.isIncomplete() )
     306        return null;
     307    Map<Way, Boolean> touchingWays = new HashMap<>();
     308    for( Node n : ring.getNodes() ) {
     309        for( OsmPrimitive p : n.getReferrers() ) {
     310        if( p instanceof Way && !p.equals(ring) ) {
     311            for( OsmPrimitive r : p.getReferrers() ) {
     312            if( r instanceof Relation && ((Relation)r).hasKey("type") && ((Relation)r).get("type").equals("multipolygon") ) {
     313                if( touchingWays.containsKey((Way)p) )
     314                touchingWays.put((Way)p, Boolean.TRUE);
     315                else
     316                touchingWays.put((Way)p, Boolean.FALSE);
     317                break;
     318            }
     319            }
     320        }
     321        }
     322    }
     323   
     324    List<TheRing> otherWays = new ArrayList<>();
     325    for( Way w : touchingWays.keySet() )
     326        if( touchingWays.get(w) ) {
     327        otherWays.add(new TheRing(w));
     328//        System.out.println("Touching ring: " + otherWays.get(otherWays.size()-1));
     329        }
     330   
     331//    for( Iterator<Way> keys = touchingWays.keySet().iterator(); keys.hasNext(); ) {
     332//        if( !touchingWays.get(keys.next()) )
     333//        keys.remove();
     334//    }
     335   
     336    // now touchingWays has only ways that touch the ring twice
     337    List<Command> commands = new ArrayList<>();
     338    TheRing theRing = new TheRing(ring); // this is actually useful
     339   
     340    for( TheRing otherRing : otherWays )
     341        theRing.collide(otherRing);
     342   
     343    theRing.putSourceWayFirst();
     344    for( TheRing otherRing : otherWays )
     345        otherRing.putSourceWayFirst();
     346   
     347    Map<Relation, Relation> relationCache = new HashMap<>();
     348    for( TheRing otherRing : otherWays )
     349        commands.addAll(otherRing.getCommands(false, relationCache));
     350    commands.addAll(theRing.getCommands(relationCache));
     351    TheRing.updateCommandsWithRelations(commands, relationCache);
     352    resultingCommands.add(new SequenceCommand(tr("Complete multipolygon for way {0}",
     353        DefaultNameFormatter.getInstance().format(ring)), commands));
     354    return theRing.getRelation();
    355355    }
    356356}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/TheRing.java

    r30737 r30738  
    3636
    3737    public TheRing( Way source ) {
    38         this.source = source;
    39         segments = new ArrayList<>(1);
    40         segments.add(new RingSegment(source));
     38    this.source = source;
     39    segments = new ArrayList<>(1);
     40    segments.add(new RingSegment(source));
    4141    }
    4242   
    4343    public static boolean areAllOfThoseRings( Collection<Way> ways ) {
    44         List<Way> rings = new ArrayList<>();
    45         for( Way way : ways ) {
    46             if( way.isClosed() )
    47                 rings.add(way);
    48             else
    49                 return false;
    50         }
    51         if( rings.isEmpty() || ways.size() == 1 )
    52             return false;
    53 
    54         // check for non-containment of rings
    55         for( int i = 0; i < rings.size() - 1; i++ ) {
    56             for( int j = i + 1; j < rings.size(); j++ ) {
    57                 PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
    58                 if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
    59                     return false;
    60             }
    61         }
    62 
    63         return true;
     44    List<Way> rings = new ArrayList<>();
     45    for( Way way : ways ) {
     46        if( way.isClosed() )
     47        rings.add(way);
     48        else
     49        return false;
     50    }
     51    if( rings.isEmpty() || ways.size() == 1 )
     52        return false;
     53
     54    // check for non-containment of rings
     55    for( int i = 0; i < rings.size() - 1; i++ ) {
     56        for( int j = i + 1; j < rings.size(); j++ ) {
     57        PolygonIntersection intersection = Geometry.polygonIntersection(rings.get(i).getNodes(), rings.get(j).getNodes());
     58        if( intersection == PolygonIntersection.FIRST_INSIDE_SECOND || intersection == PolygonIntersection.SECOND_INSIDE_FIRST )
     59            return false;
     60        }
     61    }
     62
     63    return true;
    6464    }
    6565
     
    6969     */
    7070    public static List<Relation> makeManySimpleMultipolygons( Collection<Way> selection, List<Command> commands ) {
    71         log("---------------------------------------");
    72         List<TheRing> rings = new ArrayList<>(selection.size());
    73         for( Way w : selection )
    74             rings.add(new TheRing(w));
    75         for( int i = 0; i < rings.size() - 1; i++ )
    76             for( int j = i + 1; j < rings.size(); j++ )
    77                 rings.get(i).collide(rings.get(j));
    78         redistributeSegments(rings);
    79         List<Relation> relations = new ArrayList<>();
    80         Map<Relation, Relation> relationCache = new HashMap<>();
    81         for( TheRing r : rings ) {
    82             commands.addAll(r.getCommands(relationCache));
    83             relations.add(r.getRelation());
    84         }
    85         updateCommandsWithRelations(commands, relationCache);
    86         return relations;
     71    log("---------------------------------------");
     72    List<TheRing> rings = new ArrayList<>(selection.size());
     73    for( Way w : selection )
     74        rings.add(new TheRing(w));
     75    for( int i = 0; i < rings.size() - 1; i++ )
     76        for( int j = i + 1; j < rings.size(); j++ )
     77        rings.get(i).collide(rings.get(j));
     78    redistributeSegments(rings);
     79    List<Relation> relations = new ArrayList<>();
     80    Map<Relation, Relation> relationCache = new HashMap<>();
     81    for( TheRing r : rings ) {
     82        commands.addAll(r.getCommands(relationCache));
     83        relations.add(r.getRelation());
     84    }
     85    updateCommandsWithRelations(commands, relationCache);
     86    return relations;
    8787    }
    8888
    8989    public void collide( TheRing other ) {
    90         boolean collideNoted = false;
    91         for( int i = 0; i < segments.size(); i++ ) {
    92             RingSegment segment1 = segments.get(i);
    93             if( !segment1.isReference() ) {
    94                 for( int j = 0; j < other.segments.size(); j++ ) {
    95                     RingSegment segment2 = other.segments.get(j);
    96                     if( !segment2.isReference() ) {
    97                         log("Comparing " + segment1 + " and " + segment2);
    98                         Node[] split = getSplitNodes(segment1.getNodes(), segment2.getNodes(), segment1.isRing(), segment2.isRing());
    99                         if( split != null ) {
    100                             if( !collideNoted ) {
    101                                 log("Rings for ways " + source.getUniqueId() + " and " + other.source.getUniqueId() + " collide.");
    102                                 collideNoted = true;
    103                             }
    104                             RingSegment segment = splitRingAt(i, split[0], split[1]);
    105                             RingSegment otherSegment = other.splitRingAt(j, split[2], split[3]);
    106                             if( !areSegmentsEqual(segment, otherSegment) )
    107                                 throw new IllegalArgumentException("Error: algorithm gave incorrect segments: " + segment + " and " + otherSegment);
    108                             segment.makeReference(otherSegment);
    109                         }
    110                     }
    111                     if( segment1.isReference() )
    112                         break;
    113                 }
    114             }
    115         }
     90    boolean collideNoted = false;
     91    for( int i = 0; i < segments.size(); i++ ) {
     92        RingSegment segment1 = segments.get(i);
     93        if( !segment1.isReference() ) {
     94        for( int j = 0; j < other.segments.size(); j++ ) {
     95            RingSegment segment2 = other.segments.get(j);
     96            if( !segment2.isReference() ) {
     97            log("Comparing " + segment1 + " and " + segment2);
     98            Node[] split = getSplitNodes(segment1.getNodes(), segment2.getNodes(), segment1.isRing(), segment2.isRing());
     99            if( split != null ) {
     100                if( !collideNoted ) {
     101                log("Rings for ways " + source.getUniqueId() + " and " + other.source.getUniqueId() + " collide.");
     102                collideNoted = true;
     103                }
     104                RingSegment segment = splitRingAt(i, split[0], split[1]);
     105                RingSegment otherSegment = other.splitRingAt(j, split[2], split[3]);
     106                if( !areSegmentsEqual(segment, otherSegment) )
     107                throw new IllegalArgumentException("Error: algorithm gave incorrect segments: " + segment + " and " + otherSegment);
     108                segment.makeReference(otherSegment);
     109            }
     110            }
     111            if( segment1.isReference() )
     112            break;
     113        }
     114        }
     115    }
    116116    }
    117117   
     
    120120     */
    121121    public static Node[] getSplitNodes( List<Node> nodes1, List<Node> nodes2, boolean isRing1, boolean isRing2 ) {
    122         int pos = 0;
    123         while( pos < nodes1.size() && !nodes2.contains(nodes1.get(pos)) )
    124             pos++;
    125         boolean collideFound = pos == nodes1.size();
    126         if( pos == 0 && isRing1 ) {
    127             // rewind a bit
    128             pos = nodes1.size() - 1;
    129             while( pos > 0 && nodes2.contains(nodes1.get(pos)) )
    130                 pos--;
    131             if( pos == 0 && nodes1.size() == nodes2.size() ) {
    132                 JOptionPane.showMessageDialog(Main.parent, "Two rings are equal, and this must not be.", "Multipolygon from rings", JOptionPane.ERROR_MESSAGE);
    133                 return null;
    134             }
    135             pos = pos == nodes1.size() - 1 ? 0 : pos + 1;
    136         }
    137         int firstPos = isRing1 ? pos : nodes1.size();
    138         while( !collideFound ) {
    139             log("pos=" + pos);
    140             int start1 = pos;
    141             int start2 = nodes2.indexOf(nodes1.get(start1));
    142             int last1 = incrementBy(start1, 1, nodes1.size(), isRing1);
    143             int last2 = start2;
    144             int increment2 = 0;
    145             if( last1 >= 0 ) {
    146                 last2 = incrementBy(start2, -1, nodes2.size(), isRing2);
    147                 if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
    148                     increment2 = -1;
    149                 else {
    150                     last2 = incrementBy(start2, 1, nodes2.size(), isRing2);
    151                     if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
    152                         increment2 = 1;
    153                 }
    154             }
    155             log("last1=" + last1 + " last2=" + last2 + " increment2=" + increment2);
    156             if( increment2 != 0 ) {
    157                 // find the first nodes
    158                 boolean reachedEnd = false;
    159                 while( !reachedEnd ) {
    160                     int newLast1 = incrementBy(last1, 1, nodes1.size(), isRing1);
    161                     int newLast2 = incrementBy(last2, increment2, nodes2.size(), isRing2);
    162                     if( newLast1 < 0 || newLast2 < 0 || !nodes1.get(newLast1).equals(nodes2.get(newLast2)) )
    163                         reachedEnd = true;
    164                     else {
    165                         last1 = newLast1;
    166                         last2 = newLast2;
    167                     }
    168                 }
    169                 log("last1=" + last1 + " last2=" + last2);
    170                 if( increment2 < 0 ) {
    171                     int tmp = start2;
    172                     start2 = last2;
    173                     last2 = tmp;
    174                 }
    175                 return new Node[] {nodes1.get(start1), nodes1.get(last1), nodes2.get(start2), nodes2.get(last2)};
    176             } else {
    177                 pos = last1;
    178                 while( pos != firstPos && pos >= 0 && !nodes2.contains(nodes1.get(pos)) )
    179                     pos = incrementBy(pos, 1, nodes1.size(), isRing1);
    180                 if( pos < 0 || pos == firstPos || !nodes2.contains(nodes1.get(pos)) )
    181                     collideFound = true;
    182             }
    183         }
    184         return null;
     122    int pos = 0;
     123    while( pos < nodes1.size() && !nodes2.contains(nodes1.get(pos)) )
     124        pos++;
     125    boolean collideFound = pos == nodes1.size();
     126    if( pos == 0 && isRing1 ) {
     127        // rewind a bit
     128        pos = nodes1.size() - 1;
     129        while( pos > 0 && nodes2.contains(nodes1.get(pos)) )
     130        pos--;
     131        if( pos == 0 && nodes1.size() == nodes2.size() ) {
     132        JOptionPane.showMessageDialog(Main.parent, "Two rings are equal, and this must not be.", "Multipolygon from rings", JOptionPane.ERROR_MESSAGE);
     133        return null;
     134        }
     135        pos = pos == nodes1.size() - 1 ? 0 : pos + 1;
     136    }
     137    int firstPos = isRing1 ? pos : nodes1.size();
     138    while( !collideFound ) {
     139        log("pos=" + pos);
     140        int start1 = pos;
     141        int start2 = nodes2.indexOf(nodes1.get(start1));
     142        int last1 = incrementBy(start1, 1, nodes1.size(), isRing1);
     143        int last2 = start2;
     144        int increment2 = 0;
     145        if( last1 >= 0 ) {
     146        last2 = incrementBy(start2, -1, nodes2.size(), isRing2);
     147        if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
     148            increment2 = -1;
     149        else {
     150            last2 = incrementBy(start2, 1, nodes2.size(), isRing2);
     151            if( last2 >= 0 && nodes1.get(last1).equals(nodes2.get(last2)) )
     152            increment2 = 1;
     153        }
     154        }
     155        log("last1=" + last1 + " last2=" + last2 + " increment2=" + increment2);
     156        if( increment2 != 0 ) {
     157        // find the first nodes
     158        boolean reachedEnd = false;
     159        while( !reachedEnd ) {
     160            int newLast1 = incrementBy(last1, 1, nodes1.size(), isRing1);
     161            int newLast2 = incrementBy(last2, increment2, nodes2.size(), isRing2);
     162            if( newLast1 < 0 || newLast2 < 0 || !nodes1.get(newLast1).equals(nodes2.get(newLast2)) )
     163            reachedEnd = true;
     164            else {
     165            last1 = newLast1;
     166            last2 = newLast2;
     167            }
     168        }
     169        log("last1=" + last1 + " last2=" + last2);
     170        if( increment2 < 0 ) {
     171            int tmp = start2;
     172            start2 = last2;
     173            last2 = tmp;
     174        }
     175        return new Node[] {nodes1.get(start1), nodes1.get(last1), nodes2.get(start2), nodes2.get(last2)};
     176        } else {
     177        pos = last1;
     178        while( pos != firstPos && pos >= 0 && !nodes2.contains(nodes1.get(pos)) )
     179            pos = incrementBy(pos, 1, nodes1.size(), isRing1);
     180        if( pos < 0 || pos == firstPos || !nodes2.contains(nodes1.get(pos)) )
     181            collideFound = true;
     182        }
     183    }
     184    return null;
    185185    }
    186186   
    187187    private static int incrementBy( int value, int increment, int limit1, boolean isRing ) {
    188         int result = value + increment;
    189         if( result < 0 )
    190             return isRing ? result + limit1 : -1;
    191         else if( result >= limit1 )
    192             return isRing ? result - limit1 : -1;
    193         else
    194             return result;
     188    int result = value + increment;
     189    if( result < 0 )
     190        return isRing ? result + limit1 : -1;
     191    else if( result >= limit1 )
     192        return isRing ? result - limit1 : -1;
     193    else
     194        return result;
    195195    }
    196196   
    197197    private boolean areSegmentsEqual( RingSegment seg1, RingSegment seg2 ) {
    198         List<Node> nodes1 = seg1.getNodes();
    199         List<Node> nodes2 = seg2.getNodes();
    200         int size = nodes1.size();
    201         if( size != nodes2.size() )
    202             return false;
    203         boolean reverse = size > 1 && !nodes1.get(0).equals(nodes2.get(0));
    204         for( int i = 0; i < size; i++ )
    205             if( !nodes1.get(i).equals(nodes2.get(reverse ? size-1-i : i)) )
    206                 return false;
    207         return true;
     198    List<Node> nodes1 = seg1.getNodes();
     199    List<Node> nodes2 = seg2.getNodes();
     200    int size = nodes1.size();
     201    if( size != nodes2.size() )
     202        return false;
     203    boolean reverse = size > 1 && !nodes1.get(0).equals(nodes2.get(0));
     204    for( int i = 0; i < size; i++ )
     205        if( !nodes1.get(i).equals(nodes2.get(reverse ? size-1-i : i)) )
     206        return false;
     207    return true;
    208208    }
    209209
     
    213213     */
    214214    private RingSegment splitRingAt( int segmentIndex, Node n1, Node n2 ) {
    215         if( n1.equals(n2) )
    216             throw new IllegalArgumentException("Both nodes are equal, id=" + n1.getUniqueId());
    217         RingSegment segment = segments.get(segmentIndex);
    218         boolean isRing = segment.isRing();
    219         log("Split segment " + segment + " at nodes " + n1.getUniqueId() + " and " + n2.getUniqueId());
    220         boolean reversed = segment.getNodes().indexOf(n2) < segment.getNodes().indexOf(n1);
    221         if( reversed && !isRing ) {
    222             // order nodes
    223             Node tmp = n1;
    224             n1 = n2;
    225             n2 = tmp;
    226         }
    227         RingSegment secondPart = isRing ? segment.split(n1, n2) : segment.split(n1);
    228         // if secondPart == null, then n1 == firstNode
    229         RingSegment thirdPart = isRing ? null : secondPart == null ? segment.split(n2) : secondPart.split(n2);
    230         // if secondPart == null, then thirdPart is between n1 and n2
    231         // otherwise, thirdPart is between n2 and lastNode
    232         // if thirdPart == null, then n2 == lastNode
    233         int pos = segmentIndex + 1;
    234         if( secondPart != null )
    235             segments.add(pos++, secondPart);
    236         if( thirdPart != null )
    237             segments.add(pos++, thirdPart);
    238         return isRing || secondPart == null ? segment : secondPart;
     215    if( n1.equals(n2) )
     216        throw new IllegalArgumentException("Both nodes are equal, id=" + n1.getUniqueId());
     217    RingSegment segment = segments.get(segmentIndex);
     218    boolean isRing = segment.isRing();
     219    log("Split segment " + segment + " at nodes " + n1.getUniqueId() + " and " + n2.getUniqueId());
     220    boolean reversed = segment.getNodes().indexOf(n2) < segment.getNodes().indexOf(n1);
     221    if( reversed && !isRing ) {
     222        // order nodes
     223        Node tmp = n1;
     224        n1 = n2;
     225        n2 = tmp;
     226    }
     227    RingSegment secondPart = isRing ? segment.split(n1, n2) : segment.split(n1);
     228    // if secondPart == null, then n1 == firstNode
     229    RingSegment thirdPart = isRing ? null : secondPart == null ? segment.split(n2) : secondPart.split(n2);
     230    // if secondPart == null, then thirdPart is between n1 and n2
     231    // otherwise, thirdPart is between n2 and lastNode
     232    // if thirdPart == null, then n2 == lastNode
     233    int pos = segmentIndex + 1;
     234    if( secondPart != null )
     235        segments.add(pos++, secondPart);
     236    if( thirdPart != null )
     237        segments.add(pos++, thirdPart);
     238    return isRing || secondPart == null ? segment : secondPart;
    239239    }
    240240
     
    246246     */
    247247    public static void redistributeSegments( List<TheRing> rings ) {
    248         // build segments map
    249         Map<RingSegment, TheRing> segmentMap = new HashMap<>();
    250         for( TheRing ring : rings )
    251             for( RingSegment seg : ring.segments )
    252                 if( !seg.isReference() )
    253                     segmentMap.put(seg, ring);
    254 
    255         // rearrange references
    256         for( int i = 0; i < rings.size(); i++ ) {
    257             TheRing ring = rings.get(i);
    258             if( ring.countNonReferenceSegments() == 0 ) {
    259                 // need to find one non-reference segment
    260                 for( RingSegment seg : ring.segments ) {
    261                     TheRing otherRing = segmentMap.get(seg.references);
    262                     if( otherRing.countNonReferenceSegments() > 1 ) {
    263                         // we could check for >0, but it is prone to deadlocking
    264                         seg.swapReference();
    265                     }
    266                 }
    267             }
    268         }
    269 
    270         // initializing source way for each ring
    271         for( TheRing ring : rings )
    272             ring.putSourceWayFirst();
     248    // build segments map
     249    Map<RingSegment, TheRing> segmentMap = new HashMap<>();
     250    for( TheRing ring : rings )
     251        for( RingSegment seg : ring.segments )
     252        if( !seg.isReference() )
     253            segmentMap.put(seg, ring);
     254
     255    // rearrange references
     256    for( int i = 0; i < rings.size(); i++ ) {
     257        TheRing ring = rings.get(i);
     258        if( ring.countNonReferenceSegments() == 0 ) {
     259        // need to find one non-reference segment
     260        for( RingSegment seg : ring.segments ) {
     261            TheRing otherRing = segmentMap.get(seg.references);
     262            if( otherRing.countNonReferenceSegments() > 1 ) {
     263            // we could check for >0, but it is prone to deadlocking
     264            seg.swapReference();
     265            }
     266        }
     267        }
     268    }
     269
     270    // initializing source way for each ring
     271    for( TheRing ring : rings )
     272        ring.putSourceWayFirst();
    273273    }
    274274
    275275    private int countNonReferenceSegments() {
    276         int count = 0;
    277         for( RingSegment seg : segments )
    278             if( !seg.isReference() )
    279                 count++;
    280         return count;
     276    int count = 0;
     277    for( RingSegment seg : segments )
     278        if( !seg.isReference() )
     279        count++;
     280    return count;
    281281    }
    282282
    283283    public void putSourceWayFirst() {
    284         for( RingSegment seg : segments ) {
    285             if( !seg.isReference() ) {
    286                 seg.overrideWay(source);
    287                 return;
    288             }
    289         }
     284    for( RingSegment seg : segments ) {
     285        if( !seg.isReference() ) {
     286        seg.overrideWay(source);
     287        return;
     288        }
     289    }
    290290    }
    291291   
    292292    public List<Command> getCommands() {
    293         return getCommands(true, null);
     293    return getCommands(true, null);
    294294    }
    295295   
    296296    public List<Command> getCommands( Map<Relation, Relation> relationChangeMap ) {
    297         return getCommands(true, relationChangeMap);
     297    return getCommands(true, relationChangeMap);
    298298    }
    299299   
     
    303303     */
    304304    public List<Command> getCommands( boolean createMultipolygon, Map<Relation, Relation> relationChangeMap ) {
    305         Way sourceCopy = new Way(source);
    306         if( createMultipolygon ) {
    307             Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
    308             relation = new Relation();
    309             relation.put("type", "multipolygon");
    310             for( String key : sourceCopy.keySet() ) {
     305    Way sourceCopy = new Way(source);
     306    if( createMultipolygon ) {
     307        Collection<String> linearTags = Main.pref.getCollection(PREF_MULTIPOLY + "lineartags", CreateMultipolygonAction.DEFAULT_LINEAR_TAGS);
     308        relation = new Relation();
     309        relation.put("type", "multipolygon");
     310        for( String key : sourceCopy.keySet() ) {
    311311                if( linearTags.contains(key) ) continue;
    312312                if( key.equals("natural") && sourceCopy.get("natural").equals("coastline") ) continue;
    313313                relation.put(key, sourceCopy.get(key));
    314314                sourceCopy.remove(key);
    315             }
    316         }
    317 
    318         // build a map of referencing relations
    319         Map<Relation, Integer> referencingRelations = new HashMap<>();
    320         List<Command> relationCommands = new ArrayList<>();
    321         for( OsmPrimitive p : source.getReferrers() ) {
    322             if( p instanceof Relation ) {
    323                 Relation rel = null;
    324                 if( relationChangeMap != null ) {
    325                     if( relationChangeMap.containsKey((Relation)p) )
    326                         rel = relationChangeMap.get((Relation)p);
    327                     else {
    328                         rel = new Relation((Relation)p);
    329                         relationChangeMap.put((Relation)p, rel);
    330                     }
    331                 } else {                   
    332                     rel = new Relation((Relation)p);
    333                     relationCommands.add(new ChangeCommand((Relation)p, rel));
    334                 }
    335                 for( int i = 0; i < rel.getMembersCount(); i++ )
    336                     if( rel.getMember(i).getMember().equals(source) )
    337                         referencingRelations.put(rel, Integer.valueOf(i));
    338             }
    339         }
    340         // todo: когда два кольца менÑ�ÑŽÑ‚ одно и то же отношение, в Ñ�пиÑ�ок команд добавлÑ�етÑ�Ñ�
    341         // изменение базового отношениÑ� на новое, а не предыдущего
    342         // поÑ�тому Ñ�охранÑ�етÑ�Ñ� только первое изменение
    343 
    344         List<Command> commands = new ArrayList<>();
    345         boolean foundOwnWay = false;
    346         for( RingSegment seg : segments ) {
    347             boolean needAdding = !seg.isWayConstructed();
    348             Way w = seg.constructWay(seg.isReference() ? null : sourceCopy);
    349             if( needAdding )
    350                 commands.add(new AddCommand(w));
    351             if( w.equals(source) ) {
    352                 if( createMultipolygon || !seg.getWayNodes().equals(source.getNodes()) ) {
    353                     sourceCopy.setNodes(seg.getWayNodes());
    354                     commands.add(new ChangeCommand(source, sourceCopy));
    355                 }
    356                 foundOwnWay = true;
    357             } else {
    358                 for( Relation rel : referencingRelations.keySet() ) {
    359                     int relIndex = referencingRelations.get(rel);
    360                     rel.addMember(new RelationMember(rel.getMember(relIndex).getRole(), w));
    361                 }
    362             }
    363             if( createMultipolygon )
    364                 relation.addMember(new RelationMember("outer", w));
    365         }
    366         if( !foundOwnWay )
    367             commands.add(new DeleteCommand(source));
    368         commands.addAll(relationCommands);
    369         if( createMultipolygon )
    370             commands.add(new AddCommand(relation));
    371         return commands;
     315        }
     316    }
     317
     318    // build a map of referencing relations
     319    Map<Relation, Integer> referencingRelations = new HashMap<>();
     320    List<Command> relationCommands = new ArrayList<>();
     321    for( OsmPrimitive p : source.getReferrers() ) {
     322        if( p instanceof Relation ) {
     323        Relation rel = null;
     324        if( relationChangeMap != null ) {
     325            if( relationChangeMap.containsKey((Relation)p) )
     326            rel = relationChangeMap.get((Relation)p);
     327            else {
     328            rel = new Relation((Relation)p);
     329            relationChangeMap.put((Relation)p, rel);
     330            }
     331        } else {           
     332            rel = new Relation((Relation)p);
     333            relationCommands.add(new ChangeCommand((Relation)p, rel));
     334        }
     335        for( int i = 0; i < rel.getMembersCount(); i++ )
     336            if( rel.getMember(i).getMember().equals(source) )
     337            referencingRelations.put(rel, Integer.valueOf(i));
     338        }
     339    }
     340    // todo: когда два кольца менÑ�ÑŽÑ‚ одно и то же отношение, в Ñ�пиÑ�ок команд добавлÑ�етÑ�Ñ�
     341    // изменение базового отношениÑ� на новое, а не предыдущего
     342    // поÑ�тому Ñ�охранÑ�етÑ�Ñ� только первое изменение
     343
     344    List<Command> commands = new ArrayList<>();
     345    boolean foundOwnWay = false;
     346    for( RingSegment seg : segments ) {
     347        boolean needAdding = !seg.isWayConstructed();
     348        Way w = seg.constructWay(seg.isReference() ? null : sourceCopy);
     349        if( needAdding )
     350        commands.add(new AddCommand(w));
     351        if( w.equals(source) ) {
     352        if( createMultipolygon || !seg.getWayNodes().equals(source.getNodes()) ) {
     353            sourceCopy.setNodes(seg.getWayNodes());
     354            commands.add(new ChangeCommand(source, sourceCopy));
     355        }
     356        foundOwnWay = true;
     357        } else {
     358        for( Relation rel : referencingRelations.keySet() ) {
     359            int relIndex = referencingRelations.get(rel);
     360            rel.addMember(new RelationMember(rel.getMember(relIndex).getRole(), w));
     361        }
     362        }
     363        if( createMultipolygon )
     364        relation.addMember(new RelationMember("outer", w));
     365    }
     366    if( !foundOwnWay )
     367        commands.add(new DeleteCommand(source));
     368    commands.addAll(relationCommands);
     369    if( createMultipolygon )
     370        commands.add(new AddCommand(relation));
     371    return commands;
    372372    }
    373373   
    374374    public static void updateCommandsWithRelations( List<Command> commands, Map<Relation, Relation> relationCache ) {
    375         for( Relation src : relationCache.keySet() )
    376             commands.add(new ChangeCommand(src, relationCache.get(src)));
     375    for( Relation src : relationCache.keySet() )
     376        commands.add(new ChangeCommand(src, relationCache.get(src)));
    377377    }
    378378
     
    381381     */
    382382    public Relation getRelation() {
    383         return relation;
     383    return relation;
    384384    }
    385385
    386386    @Override
    387387    public String toString() {
    388         StringBuilder sb = new StringBuilder("TheRing@");
    389         sb.append(this.hashCode()).append('[').append("wayId: ").append(source == null ? "null" : source.getUniqueId()).append("; segments: ");
    390         if( segments.isEmpty() )
    391             sb.append("empty");
    392         else {
    393             sb.append(segments.get(0));
    394             for( int i = 1; i < segments.size(); i++ )
    395                 sb.append(", ").append(segments.get(i));
    396         }
    397         return sb.append(']').toString();
     388    StringBuilder sb = new StringBuilder("TheRing@");
     389    sb.append(this.hashCode()).append('[').append("wayId: ").append(source == null ? "null" : source.getUniqueId()).append("; segments: ");
     390    if( segments.isEmpty() )
     391        sb.append("empty");
     392    else {
     393        sb.append(segments.get(0));
     394        for( int i = 1; i < segments.size(); i++ )
     395        sb.append(", ").append(segments.get(i));
     396    }
     397    return sb.append(']').toString();
    398398    }
    399399
     
    402402     */
    403403    /*private static void closePolygon( List<Node> base, List<Node> append ) {
    404         if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
    405             List<Node> ap2 = new ArrayList<Node>(append);
    406             Collections.reverse(ap2);
    407             append = ap2;
    408         }
    409         base.remove(base.size() - 1);
    410         base.addAll(append);
     404    if( append.get(0).equals(base.get(0)) && append.get(append.size() - 1).equals(base.get(base.size() - 1)) ) {
     405        List<Node> ap2 = new ArrayList<Node>(append);
     406        Collections.reverse(ap2);
     407        append = ap2;
     408    }
     409    base.remove(base.size() - 1);
     410    base.addAll(append);
    411411    }*/
    412412
     
    415415     */
    416416    /*private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) {
    417         EastNorth en1 = n1.getEastNorth();
    418         EastNorth en2 = n2.getEastNorth();
    419         Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
    420         return Geometry.nodeInsidePolygon(testNode, polygon);
     417    EastNorth en1 = n1.getEastNorth();
     418    EastNorth en2 = n2.getEastNorth();
     419    Node testNode = new Node(new EastNorth((en1.east() + en2.east()) / 2.0, (en1.north() + en2.north()) / 2.0));
     420    return Geometry.nodeInsidePolygon(testNode, polygon);
    421421    }*/
    422422   
    423423    private static void log( String s ) {
    424 //      System.out.println(s);
     424//    System.out.println(s);
    425425    }
    426426   
    427427    private static class RingSegment {
    428         private List<Node> nodes;
    429         private RingSegment references;
    430         private Way resultingWay = null;
    431         private boolean wasTemplateApplied = false;
    432         private boolean isRing;
    433 
    434         /*private RingSegment() {
    435         }*/
    436 
    437         public RingSegment( Way w ) {
    438             this(w.getNodes());
    439         }
    440 
    441         public RingSegment( List<Node> nodes ) {
    442             this.nodes = nodes;
    443             isRing = nodes.size() > 1 && nodes.get(0).equals(nodes.get(nodes.size() - 1));
    444             if( isRing )
    445                 nodes.remove(nodes.size() - 1);
    446             references = null;
    447         }
    448 
    449         /*public RingSegment( RingSegment ref ) {
    450             this.nodes = null;
    451             this.references = ref;
    452         }*/
    453 
    454         /**
    455         * Splits this segment at node n. Retains nodes 0..n and moves
    456         * nodes n..N to a separate segment that is returned.
    457         * @param n node at which to split.
    458         * @return new segment, {@code null} if splitting is unnecessary.
    459         */
    460         public RingSegment split( Node n ) {
    461             if( nodes == null )
    462                 throw new IllegalArgumentException("Cannot split segment: it is a reference");
    463             int pos = nodes.indexOf(n);
    464             if( pos <= 0 || pos >= nodes.size() - 1 )
    465                 return null;
    466             List<Node> newNodes = new ArrayList<>(nodes.subList(pos, nodes.size()));
    467             nodes.subList(pos + 1, nodes.size()).clear();
    468             return new RingSegment(newNodes);
    469         }
    470 
    471         /**
    472         * Split this segment as a way at two nodes. If one of them is null or at the end,
    473         * split as an arc. Note: order of nodes is important.
    474         * @return A new segment from n2 to n1.
    475         */
    476         public RingSegment split( Node n1, Node n2 ) {
    477             if( nodes == null )
    478                 throw new IllegalArgumentException("Cannot split segment: it is a reference");
    479             if( !isRing ) {
    480                 if( n1 == null || nodes.get(0).equals(n1) || nodes.get(nodes.size() - 1).equals(n1) )
    481                     return split(n2);
    482                 if( n2 == null || nodes.get(0).equals(n2) || nodes.get(nodes.size() - 1).equals(n2) )
    483                     return split(n1);
    484                 throw new IllegalArgumentException("Split for two nodes is called for not-ring: " + this);
    485             }
    486             int pos1 = nodes.indexOf(n1);
    487             int pos2 = nodes.indexOf(n2);
    488             if( pos1 == pos2 )
    489                 return null;
    490 
    491             List<Node> newNodes = new ArrayList<>();
    492             if( pos2 > pos1 ) {
    493                 newNodes.addAll(nodes.subList(pos2, nodes.size()));
    494                 newNodes.addAll(nodes.subList(0, pos1 + 1));
    495                 if( pos2 + 1 < nodes.size() )
    496                     nodes.subList(pos2 + 1, nodes.size()).clear();
    497                 if( pos1 > 0 )
    498                     nodes.subList(0, pos1).clear();
    499             } else {
    500                 newNodes.addAll(nodes.subList(pos2, pos1 + 1));
    501                 nodes.addAll(new ArrayList<>(nodes.subList(0, pos2 + 1)));
    502                 nodes.subList(0, pos1).clear();
    503             }
    504             isRing = false;
    505             return new RingSegment(newNodes);
    506         }
    507 
    508         public List<Node> getNodes() {
    509             return nodes == null ? references.nodes : nodes;
    510         }
    511 
    512         public List<Node> getWayNodes() {
    513             if( nodes == null )
    514                 throw new IllegalArgumentException("Won't give you wayNodes: it is a reference");
    515             List<Node> wayNodes = new ArrayList<>(nodes);
    516             if( isRing )
    517                 wayNodes.add(wayNodes.get(0));
    518             return wayNodes;
    519         }
    520 
    521         public boolean isReference() {
    522             return nodes == null;
    523         }
    524 
    525         public boolean isRing() {
    526             return isRing;
    527         }
    528 
    529         public void makeReference( RingSegment segment ) {
    530             log(this + " was made a reference to " + segment);
    531             this.nodes = null;
    532             this.references = segment;
    533         }
    534 
    535         public void swapReference() {
    536             this.nodes = references.nodes;
    537             references.nodes = null;
    538             references.references = this;
    539             this.references = null;
    540         }
    541 
    542         public boolean isWayConstructed() {
    543             return isReference() ? references.isWayConstructed() : resultingWay != null;
    544         }
    545 
    546         public Way constructWay( Way template ) {
    547             if( isReference() )
    548                 return references.constructWay(template);
    549             if( resultingWay == null ) {
    550                 resultingWay = new Way();
    551                 resultingWay.setNodes(getWayNodes());
    552             }
    553             if( template != null && !wasTemplateApplied ) {
    554                 resultingWay.setKeys(template.getKeys());
    555                 wasTemplateApplied = true;
    556             }
    557             return resultingWay;
    558         }
    559 
    560         public void overrideWay( Way source ) {
    561             if( isReference() )
    562                 references.overrideWay(source);
    563             else {
    564                 resultingWay = source;
    565                 wasTemplateApplied = true;
    566             }
    567         }
    568 
    569         /**
    570         * Compares two segments with respect to referencing.
    571         * @return true if ways are equals, or one references another.
    572         */
    573         /*public boolean isReferencingEqual( RingSegment other ) {
    574             return this.equals(other) || (other.isReference() && other.references == this) || (isReference() && references == other);
    575         }*/
    576 
    577         @Override
    578         public String toString() {
    579             StringBuilder sb = new StringBuilder("RingSegment@");
    580             sb.append(this.hashCode()).append('[');
    581             if( isReference() )
    582                 sb.append("references ").append(references.hashCode());
    583             else if( nodes.isEmpty() )
    584                 sb.append("empty");
    585             else {
    586                 if( isRing )
    587                     sb.append("ring:");
    588                 sb.append(nodes.get(0).getUniqueId());
    589                 for( int i = 1; i < nodes.size(); i++ )
    590                     sb.append(',').append(nodes.get(i).getUniqueId());
    591             }
    592             return sb.append(']').toString();
    593         }
     428    private List<Node> nodes;
     429    private RingSegment references;
     430    private Way resultingWay = null;
     431    private boolean wasTemplateApplied = false;
     432    private boolean isRing;
     433
     434    /*private RingSegment() {
     435    }*/
     436
     437    public RingSegment( Way w ) {
     438        this(w.getNodes());
     439    }
     440
     441    public RingSegment( List<Node> nodes ) {
     442        this.nodes = nodes;
     443        isRing = nodes.size() > 1 && nodes.get(0).equals(nodes.get(nodes.size() - 1));
     444        if( isRing )
     445        nodes.remove(nodes.size() - 1);
     446        references = null;
     447    }
     448
     449    /*public RingSegment( RingSegment ref ) {
     450        this.nodes = null;
     451        this.references = ref;
     452    }*/
     453
     454    /**
     455    * Splits this segment at node n. Retains nodes 0..n and moves
     456    * nodes n..N to a separate segment that is returned.
     457    * @param n node at which to split.
     458    * @return new segment, {@code null} if splitting is unnecessary.
     459    */
     460    public RingSegment split( Node n ) {
     461        if( nodes == null )
     462        throw new IllegalArgumentException("Cannot split segment: it is a reference");
     463        int pos = nodes.indexOf(n);
     464        if( pos <= 0 || pos >= nodes.size() - 1 )
     465        return null;
     466        List<Node> newNodes = new ArrayList<>(nodes.subList(pos, nodes.size()));
     467        nodes.subList(pos + 1, nodes.size()).clear();
     468        return new RingSegment(newNodes);
     469    }
     470
     471    /**
     472    * Split this segment as a way at two nodes. If one of them is null or at the end,
     473    * split as an arc. Note: order of nodes is important.
     474    * @return A new segment from n2 to n1.
     475    */
     476    public RingSegment split( Node n1, Node n2 ) {
     477        if( nodes == null )
     478        throw new IllegalArgumentException("Cannot split segment: it is a reference");
     479        if( !isRing ) {
     480        if( n1 == null || nodes.get(0).equals(n1) || nodes.get(nodes.size() - 1).equals(n1) )
     481            return split(n2);
     482        if( n2 == null || nodes.get(0).equals(n2) || nodes.get(nodes.size() - 1).equals(n2) )
     483            return split(n1);
     484        throw new IllegalArgumentException("Split for two nodes is called for not-ring: " + this);
     485        }
     486        int pos1 = nodes.indexOf(n1);
     487        int pos2 = nodes.indexOf(n2);
     488        if( pos1 == pos2 )
     489        return null;
     490
     491        List<Node> newNodes = new ArrayList<>();
     492        if( pos2 > pos1 ) {
     493        newNodes.addAll(nodes.subList(pos2, nodes.size()));
     494        newNodes.addAll(nodes.subList(0, pos1 + 1));
     495        if( pos2 + 1 < nodes.size() )
     496            nodes.subList(pos2 + 1, nodes.size()).clear();
     497        if( pos1 > 0 )
     498            nodes.subList(0, pos1).clear();
     499        } else {
     500        newNodes.addAll(nodes.subList(pos2, pos1 + 1));
     501        nodes.addAll(new ArrayList<>(nodes.subList(0, pos2 + 1)));
     502        nodes.subList(0, pos1).clear();
     503        }
     504        isRing = false;
     505        return new RingSegment(newNodes);
     506    }
     507
     508    public List<Node> getNodes() {
     509        return nodes == null ? references.nodes : nodes;
     510    }
     511
     512    public List<Node> getWayNodes() {
     513        if( nodes == null )
     514        throw new IllegalArgumentException("Won't give you wayNodes: it is a reference");
     515        List<Node> wayNodes = new ArrayList<>(nodes);
     516        if( isRing )
     517        wayNodes.add(wayNodes.get(0));
     518        return wayNodes;
     519    }
     520
     521    public boolean isReference() {
     522        return nodes == null;
     523    }
     524
     525    public boolean isRing() {
     526        return isRing;
     527    }
     528
     529    public void makeReference( RingSegment segment ) {
     530        log(this + " was made a reference to " + segment);
     531        this.nodes = null;
     532        this.references = segment;
     533    }
     534
     535    public void swapReference() {
     536        this.nodes = references.nodes;
     537        references.nodes = null;
     538        references.references = this;
     539        this.references = null;
     540    }
     541
     542    public boolean isWayConstructed() {
     543        return isReference() ? references.isWayConstructed() : resultingWay != null;
     544    }
     545
     546    public Way constructWay( Way template ) {
     547        if( isReference() )
     548        return references.constructWay(template);
     549        if( resultingWay == null ) {
     550        resultingWay = new Way();
     551        resultingWay.setNodes(getWayNodes());
     552        }
     553        if( template != null && !wasTemplateApplied ) {
     554        resultingWay.setKeys(template.getKeys());
     555        wasTemplateApplied = true;
     556        }
     557        return resultingWay;
     558    }
     559
     560    public void overrideWay( Way source ) {
     561        if( isReference() )
     562        references.overrideWay(source);
     563        else {
     564        resultingWay = source;
     565        wasTemplateApplied = true;
     566        }
     567    }
     568
     569    /**
     570    * Compares two segments with respect to referencing.
     571    * @return true if ways are equals, or one references another.
     572    */
     573    /*public boolean isReferencingEqual( RingSegment other ) {
     574        return this.equals(other) || (other.isReference() && other.references == this) || (isReference() && references == other);
     575    }*/
     576
     577    @Override
     578    public String toString() {
     579        StringBuilder sb = new StringBuilder("RingSegment@");
     580        sb.append(this.hashCode()).append('[');
     581        if( isReference() )
     582        sb.append("references ").append(references.hashCode());
     583        else if( nodes.isEmpty() )
     584        sb.append("empty");
     585        else {
     586        if( isRing )
     587            sb.append("ring:");
     588        sb.append(nodes.get(0).getUniqueId());
     589        for( int i = 1; i < nodes.size(); i++ )
     590            sb.append(',').append(nodes.get(i).getUniqueId());
     591        }
     592        return sb.append(']').toString();
     593    }
    594594    }
    595595}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/AssociatedStreetFixer.java

    r30737 r30738  
    1919public class AssociatedStreetFixer extends RelationFixer {
    2020
    21         public AssociatedStreetFixer() {
    22                 super("associatedStreet");
    23         }
    24 
    25         @Override
    26         public boolean isRelationGood(Relation rel) {
    27                 for (RelationMember m : rel.getMembers()) {
    28                 if (m.getType().equals(OsmPrimitiveType.NODE) && !"house".equals(m.getRole())) {
    29                     setWarningMessage(tr("Node without ''house'' role found"));
    30                         return false;
    31                 }
    32                 if (m.getType().equals(OsmPrimitiveType.WAY) && !("house".equals(m.getRole()) || "street".equals(m.getRole()))) {
    33                     setWarningMessage(tr("Way without ''house'' or ''street'' role found"));
    34                     return false;
    35                 }
    36                 if (m.getType().equals(OsmPrimitiveType.RELATION) && !"house".equals(m.getRole())) {
    37                     setWarningMessage(tr("Relation without ''house'' role found"));
    38                         return false;
    39                 }
    40         }
    41                 // relation should have name
    42                 if (!rel.hasKey("name")) {
    43                     setWarningMessage(tr("Relation does not have name"));
    44                         return false;
    45                 }
    46                 // check that all street members have same name as relation (???)
    47                 String streetName = rel.get("name");
    48                 if (streetName == null) streetName = "";
    49                 for (RelationMember m : rel.getMembers()) {
    50                         if ("street".equals(m.getRole()) && !streetName.equals(m.getWay().get("name"))) {
    51                             String anotherName = m.getWay().get("name");
    52                             if (anotherName != null && !anotherName.isEmpty()) {
    53                             setWarningMessage(tr("Relation has streets with different names"));
    54                             return false;
    55                             }
    56                         }
    57                 }
    58                 clearWarningMessage();
    59                 return true;
    60         }
     21    public AssociatedStreetFixer() {
     22        super("associatedStreet");
     23    }
    6124
    6225    @Override
    63         public Command fixRelation(Relation source) {
    64                 // any way with highway tag -> street
    65                 // any way/point/relation with addr:housenumber=* or building=* or type=multipolygon -> house
    66                 // name - check which name is most used in street members and add to relation
    67                 // copy this name to the other street members (???)
    68                 Relation rel = new Relation(source);
    69                 boolean fixed = false;
     26    public boolean isRelationGood(Relation rel) {
     27        for (RelationMember m : rel.getMembers()) {
     28            if (m.getType().equals(OsmPrimitiveType.NODE) && !"house".equals(m.getRole())) {
     29                setWarningMessage(tr("Node without ''house'' role found"));
     30                return false;
     31            }
     32            if (m.getType().equals(OsmPrimitiveType.WAY) && !("house".equals(m.getRole()) || "street".equals(m.getRole()))) {
     33                setWarningMessage(tr("Way without ''house'' or ''street'' role found"));
     34                return false;
     35            }
     36            if (m.getType().equals(OsmPrimitiveType.RELATION) && !"house".equals(m.getRole())) {
     37                setWarningMessage(tr("Relation without ''house'' role found"));
     38                return false;
     39            }
     40        }
     41        // relation should have name
     42        if (!rel.hasKey("name")) {
     43            setWarningMessage(tr("Relation does not have name"));
     44            return false;
     45        }
     46        // check that all street members have same name as relation (???)
     47        String streetName = rel.get("name");
     48        if (streetName == null) streetName = "";
     49        for (RelationMember m : rel.getMembers()) {
     50            if ("street".equals(m.getRole()) && !streetName.equals(m.getWay().get("name"))) {
     51                String anotherName = m.getWay().get("name");
     52                if (anotherName != null && !anotherName.isEmpty()) {
     53                    setWarningMessage(tr("Relation has streets with different names"));
     54                    return false;
     55                }
     56            }
     57        }
     58        clearWarningMessage();
     59        return true;
     60    }
    7061
    71                 for (int i = 0; i < rel.getMembersCount(); i++) {
    72                         RelationMember m = rel.getMember(i);
     62    @Override
     63    public Command fixRelation(Relation source) {
     64        // any way with highway tag -> street
     65        // any way/point/relation with addr:housenumber=* or building=* or type=multipolygon -> house
     66        // name - check which name is most used in street members and add to relation
     67        // copy this name to the other street members (???)
     68        Relation rel = new Relation(source);
     69        boolean fixed = false;
    7370
    74                         if (m.isNode()) {
    75                                 Node node = m.getNode();
    76                                 if (!"house".equals(m.getRole()) &&
    77                                                 (node.hasKey("building") || node.hasKey("addr:housenumber"))) {
    78                                         fixed = true;
    79                                         rel.setMember(i, new RelationMember("house", node));
    80                                 }
    81                         } else if (m.isWay()) {
    82                                 Way way = m.getWay();
    83                                 if (!"street".equals(m.getRole()) && way.hasKey("highway")) {
    84                                         fixed = true;
    85                                         rel.setMember(i, new RelationMember("street", way));
    86                                 } else if (!"house".equals(m.getRole()) &&
    87                                                 (way.hasKey("building") || way.hasKey("addr:housenumber"))) {
    88                                         fixed = true;
    89                                         rel.setMember(i,  new RelationMember("house", way));
    90                                 }
    91                         } else if (m.isRelation()) {
    92                                 Relation relation = m.getRelation();
    93                                 if (!"house".equals(m.getRole()) &&
    94                                                 (relation.hasKey("building") || relation.hasKey("addr:housenumber") || "multipolygon".equals(relation.get("type")))) {
    95                                         fixed = true;
    96                                         rel.setMember(i, new RelationMember("house", relation));
    97                                 }
    98                         }
    99                 }
     71        for (int i = 0; i < rel.getMembersCount(); i++) {
     72            RelationMember m = rel.getMember(i);
    10073
    101                 // fill relation name
    102                 Map<String, Integer> streetNames = new HashMap<>();
    103                 for (RelationMember m : rel.getMembers())
    104                         if ("street".equals(m.getRole()) && m.isWay()) {
    105                                 String name = m.getWay().get("name");
    106                                 if (name == null || name.isEmpty()) continue;
     74            if (m.isNode()) {
     75                Node node = m.getNode();
     76                if (!"house".equals(m.getRole()) &&
     77                        (node.hasKey("building") || node.hasKey("addr:housenumber"))) {
     78                    fixed = true;
     79                    rel.setMember(i, new RelationMember("house", node));
     80                }
     81            } else if (m.isWay()) {
     82                Way way = m.getWay();
     83                if (!"street".equals(m.getRole()) && way.hasKey("highway")) {
     84                    fixed = true;
     85                    rel.setMember(i, new RelationMember("street", way));
     86                } else if (!"house".equals(m.getRole()) &&
     87                        (way.hasKey("building") || way.hasKey("addr:housenumber"))) {
     88                    fixed = true;
     89                    rel.setMember(i,  new RelationMember("house", way));
     90                }
     91            } else if (m.isRelation()) {
     92                Relation relation = m.getRelation();
     93                if (!"house".equals(m.getRole()) &&
     94                        (relation.hasKey("building") || relation.hasKey("addr:housenumber") || "multipolygon".equals(relation.get("type")))) {
     95                    fixed = true;
     96                    rel.setMember(i, new RelationMember("house", relation));
     97                }
     98            }
     99        }
    107100
    108                                 Integer count = streetNames.get(name);
     101        // fill relation name
     102        Map<String, Integer> streetNames = new HashMap<>();
     103        for (RelationMember m : rel.getMembers())
     104            if ("street".equals(m.getRole()) && m.isWay()) {
     105                String name = m.getWay().get("name");
     106                if (name == null || name.isEmpty()) continue;
    109107
    110                                 streetNames.put(name, count != null? count + 1 : 1);
    111                         }
    112                 String commonName = "";
    113                 Integer commonCount = 0;
    114                 for (Map.Entry<String, Integer> entry : streetNames.entrySet()) {
    115                         if (entry.getValue() > commonCount) {
    116                                 commonCount = entry.getValue();
    117                                 commonName = entry.getKey();
    118                         }
    119                 }
     108                Integer count = streetNames.get(name);
    120109
    121                 if (!rel.hasKey("name") && !commonName.isEmpty()) {
    122                         fixed = true;
    123                         rel.put("name", commonName);
    124                 } else {
    125                         commonName = ""; // set empty common name - if we already have name on relation, do not overwrite it
    126                 }
     110                streetNames.put(name, count != null? count + 1 : 1);
     111            }
     112        String commonName = "";
     113        Integer commonCount = 0;
     114        for (Map.Entry<String, Integer> entry : streetNames.entrySet()) {
     115            if (entry.getValue() > commonCount) {
     116                commonCount = entry.getValue();
     117                commonName = entry.getKey();
     118            }
     119        }
    127120
    128                 List<Command> commandList = new ArrayList<>();
    129                 if (fixed) {
    130                         commandList.add(new ChangeCommand(source, rel));
    131                 }
     121        if (!rel.hasKey("name") && !commonName.isEmpty()) {
     122            fixed = true;
     123            rel.put("name", commonName);
     124        } else {
     125            commonName = ""; // set empty common name - if we already have name on relation, do not overwrite it
     126        }
    132127
    133                 /*if (!commonName.isEmpty())
    134                 // fill common name to streets
    135                 for (RelationMember m : rel.getMembers())
    136                         if ("street".equals(m.getRole()) && m.isWay()) {
    137                                 String name = m.getWay().get("name");
    138                                 if (commonName.equals(name)) continue;
     128        List<Command> commandList = new ArrayList<>();
     129        if (fixed) {
     130            commandList.add(new ChangeCommand(source, rel));
     131        }
    139132
    140                                 // TODO: ask user if he really wants to overwrite street name??
     133        /*if (!commonName.isEmpty())
     134        // fill common name to streets
     135        for (RelationMember m : rel.getMembers())
     136            if ("street".equals(m.getRole()) && m.isWay()) {
     137                String name = m.getWay().get("name");
     138                if (commonName.equals(name)) continue;
    141139
    142                                 Way oldWay = m.getWay();
    143                                 Way newWay = new Way(oldWay);
    144                                 newWay.put("name", commonName);
     140                // TODO: ask user if he really wants to overwrite street name??
    145141
    146                                 commandList.add(new ChangeCommand(oldWay, newWay));
    147                         }
    148                 */
    149                 // return results
    150                 if (commandList.size() == 0)
    151                         return null;
    152                 if (commandList.size() == 1)
    153                         return commandList.get(0);
    154                 return new SequenceCommand(tr("fix associatedStreet relation"), commandList);
    155         }
     142                Way oldWay = m.getWay();
     143                Way newWay = new Way(oldWay);
     144                newWay.put("name", commonName);
     145
     146                commandList.add(new ChangeCommand(oldWay, newWay));
     147            }
     148        */
     149        // return results
     150        if (commandList.size() == 0)
     151            return null;
     152        if (commandList.size() == 1)
     153            return commandList.get(0);
     154        return new SequenceCommand(tr("fix associatedStreet relation"), commandList);
     155    }
    156156}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/BoundaryFixer.java

    r28762 r30738  
    1616public class BoundaryFixer extends MultipolygonFixer {
    1717
    18         public BoundaryFixer() {
    19                 super("boundary", "multipolygon");
    20         }
     18    public BoundaryFixer() {
     19        super("boundary", "multipolygon");
     20    }
    2121
    22         /**
    23         * For boundary relations both "boundary" and "multipolygon" types are applicable, but
    24         * it should also have key boundary=administrative to be fully boundary.
    25         * @see http://wiki.openstreetmap.org/wiki/Relation:boundary
    26         */
    27         @Override
    28         public boolean isFixerApplicable(Relation rel) {
    29                 return super.isFixerApplicable(rel) && "administrative".equals(rel.get("boundary"));
    30         }
     22    /**
     23    * For boundary relations both "boundary" and "multipolygon" types are applicable, but
     24    * it should also have key boundary=administrative to be fully boundary.
     25    * @see http://wiki.openstreetmap.org/wiki/Relation:boundary
     26    */
     27    @Override
     28    public boolean isFixerApplicable(Relation rel) {
     29        return super.isFixerApplicable(rel) && "administrative".equals(rel.get("boundary"));
     30    }
    3131
    32         @Override
    33         public boolean isRelationGood(Relation rel) {
    34                 for( RelationMember m : rel.getMembers() ) {
     32    @Override
     33    public boolean isRelationGood(Relation rel) {
     34        for( RelationMember m : rel.getMembers() ) {
    3535            if (m.getType().equals(OsmPrimitiveType.RELATION) && !"subarea".equals(m.getRole())) {
    3636                setWarningMessage(tr("Relation without ''subarea'' role found"));
     
    4343            if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) {
    4444                setWarningMessage(tr("Way without ''inner'' or ''outer'' role found"));
    45                                 return false;
     45                return false;
    4646            }
    4747        }
    48                 clearWarningMessage();
    49                 return true;
    50         }
     48        clearWarningMessage();
     49        return true;
     50    }
    5151
    52         @Override
    53         public Command fixRelation(Relation rel) {
    54                 Relation r = rel;
    55                 Relation rr = fixMultipolygonRoles(r);
    56                 boolean fixed = false;
    57                 if (rr != null) {
    58                         fixed = true;
    59                         r = rr;
    60                 }
    61                 rr = fixBoundaryRoles(r);
    62                 if (rr != null) {
    63                         fixed = true;
    64                         r = rr;
    65                 }
    66                 return fixed ? new ChangeCommand(rel, r) : null;
    67         }
     52    @Override
     53    public Command fixRelation(Relation rel) {
     54        Relation r = rel;
     55        Relation rr = fixMultipolygonRoles(r);
     56        boolean fixed = false;
     57        if (rr != null) {
     58            fixed = true;
     59            r = rr;
     60        }
     61        rr = fixBoundaryRoles(r);
     62        if (rr != null) {
     63            fixed = true;
     64            r = rr;
     65        }
     66        return fixed ? new ChangeCommand(rel, r) : null;
     67    }
    6868
    69         private Relation fixBoundaryRoles( Relation source ) {
     69    private Relation fixBoundaryRoles( Relation source ) {
    7070        Relation r = new Relation(source);
    7171        boolean fixed = false;
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/MultipolygonFixer.java

    r30737 r30738  
    2222public class MultipolygonFixer extends RelationFixer {
    2323
    24         public MultipolygonFixer() {
    25                 super("multipolygon");
    26         }
     24    public MultipolygonFixer() {
     25        super("multipolygon");
     26    }
    2727
    28         protected MultipolygonFixer(String...types) {
    29                 super(types);
    30         }
     28    protected MultipolygonFixer(String...types) {
     29        super(types);
     30    }
    3131
    3232
    33         @Override
    34         public boolean isRelationGood(Relation rel) {
    35                 for (RelationMember m : rel.getMembers())
    36                         if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) {
    37                             setWarningMessage(tr("Way without ''inner'' or ''outer'' role found"));
    38                             return false;
    39                         }
    40                 clearWarningMessage();
    41                 return true;
    42         }
     33    @Override
     34    public boolean isRelationGood(Relation rel) {
     35        for (RelationMember m : rel.getMembers())
     36            if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) {
     37                setWarningMessage(tr("Way without ''inner'' or ''outer'' role found"));
     38                return false;
     39            }
     40        clearWarningMessage();
     41        return true;
     42    }
    4343
    44         @Override
    45         public Command fixRelation(Relation rel) {
    46                 Relation rr = fixMultipolygonRoles(rel);
    47                 return rr != null? new ChangeCommand(rel, rr) : null;
    48         }
     44    @Override
     45    public Command fixRelation(Relation rel) {
     46        Relation rr = fixMultipolygonRoles(rel);
     47        return rr != null? new ChangeCommand(rel, rr) : null;
     48    }
    4949
    50         /**
     50    /**
    5151     * Basically, created multipolygon from scratch, and if successful, replace roles with new ones.
    5252     */
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/NothingFixer.java

    r28693 r30738  
    99public class NothingFixer extends RelationFixer {
    1010
    11         public NothingFixer() {
    12                 super("");
    13         }
    14         @Override
    15         public boolean isFixerApplicable(Relation rel) {
    16                 return true;
    17         }
    18         @Override
    19         public boolean isRelationGood(Relation rel) {
    20                 return true;
    21         }
     11    public NothingFixer() {
     12        super("");
     13    }
     14    @Override
     15    public boolean isFixerApplicable(Relation rel) {
     16        return true;
     17    }
     18    @Override
     19    public boolean isRelationGood(Relation rel) {
     20        return true;
     21    }
    2222
    23         @Override
    24         public Command fixRelation(Relation rel) {
    25                 return null;
    26         }
     23    @Override
     24    public Command fixRelation(Relation rel) {
     25        return null;
     26    }
    2727
    2828}
  • applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/RelationFixer.java

    r30737 r30738  
    1515public abstract class RelationFixer {
    1616
    17         private List<String> applicableTypes;
    18         private SortAndFixAction sortAndFixAction;
     17    private List<String> applicableTypes;
     18    private SortAndFixAction sortAndFixAction;
    1919
    20         /**
    21         * Construct new RelationFixer by a list of applicable types
    22         * @param types
    23         */
    24         public RelationFixer(String... types) {
    25             applicableTypes = new ArrayList<>();
    26                 for(String type: types) {
    27                         applicableTypes.add(type);
    28                 }
    29         }
     20    /**
     21    * Construct new RelationFixer by a list of applicable types
     22    * @param types
     23    */
     24    public RelationFixer(String... types) {
     25        applicableTypes = new ArrayList<>();
     26        for(String type: types) {
     27            applicableTypes.add(type);
     28        }
     29    }
    3030
    31         /**
    32         * Check if given relation is of needed type. You may override this method to check first type
    33         * and then check desired relation properties.
    34         * Note that this only verifies if current RelationFixer can be used to check and fix given relation
    35         * Deeper relation checking is at {@link isRelationGood}
    36         *
    37         * @param rel Relation to check
    38         * @return true if relation can be verified by current RelationFixer
    39         */
    40         public boolean isFixerApplicable(Relation rel) {
    41                 if (rel == null)
    42                         return false;
    43                 if (!rel.hasKey("type"))
    44                         return false;
     31    /**
     32    * Check if given relation is of needed type. You may override this method to check first type
     33    * and then check desired relation properties.
     34    * Note that this only verifies if current RelationFixer can be used to check and fix given relation
     35    * Deeper relation checking is at {@link isRelationGood}
     36    *
     37    * @param rel Relation to check
     38    * @return true if relation can be verified by current RelationFixer
     39    */
     40    public boolean isFixerApplicable(Relation rel) {
     41        if (rel == null)
     42            return false;
     43        if (!rel.hasKey("type"))
     44            return false;
    4545
    46                 String type = rel.get("type");
    47                 for(String oktype: applicableTypes)
    48                         if (oktype.equals(type))
    49                                 return true;
     46        String type = rel.get("type");
     47        for(String oktype: applicableTypes)
     48            if (oktype.equals(type))
     49                return true;
    5050
    51                 return false;
    52         }
     51        return false;
     52    }
    5353
    54         /**
    55         * Check if given relation is OK. That means if all roles are given properly, all tags exist as expected etc.
    56         * Should be written in children classes.
    57         *
    58         * @param rel Relation to verify
    59         * @return true if given relation is OK
    60         */
    61         public abstract boolean isRelationGood(Relation rel);
     54    /**
     55    * Check if given relation is OK. That means if all roles are given properly, all tags exist as expected etc.
     56    * Should be written in children classes.
     57    *
     58    * @param rel Relation to verify
     59    * @return true if given relation is OK
     60    */
     61    public abstract boolean isRelationGood(Relation rel);
    6262
    63         /**
    64         * Fix relation and return new relation with fixed tags, roles etc.
    65         * Note that is not obligatory to return true for isRelationGood for new relation
    66         *
    67         * @param rel Relation to fix
    68         * @return command that fixes the relation {@code null} if it cannot be fixed or is already OK
    69         */
    70         public abstract Command fixRelation(Relation rel);
     63    /**
     64    * Fix relation and return new relation with fixed tags, roles etc.
     65    * Note that is not obligatory to return true for isRelationGood for new relation
     66    *
     67    * @param rel Relation to fix
     68    * @return command that fixes the relation {@code null} if it cannot be fixed or is already OK
     69    */
     70    public abstract Command fixRelation(Relation rel);
    7171
    7272    public void setFixAction(SortAndFixAction sortAndFixAction) {
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java

    r30737 r30738  
    6868import org.openstreetmap.josm.gui.ExtendedDialog;
    6969import org.openstreetmap.josm.gui.widgets.MultiSplitLayout;
     70import org.openstreetmap.josm.gui.widgets.MultiSplitLayout.Node;
    7071import org.openstreetmap.josm.gui.widgets.MultiSplitPane;
    71 import org.openstreetmap.josm.gui.widgets.MultiSplitLayout.Node;
    7272import org.openstreetmap.josm.plugins.roadsigns.RoadSignsPlugin.PresetMetaData;
    7373import org.openstreetmap.josm.plugins.roadsigns.Sign.SignParameter;
     
    103103    protected JEditorPane info;
    104104    protected JScrollPane scrollInfo;
    105    
     105
    106106    private MultiSplitPane multiSplitPane;
    107107
     
    150150                Node model = multiSplitPane.getMultiSplitLayout().getModel();
    151151                File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml");
    152                 try {
     152                try (
    153153                    XMLEncoder xmlenc = new XMLEncoder(
    154154                            new BufferedOutputStream(new FileOutputStream(f))
    155                     );
     155                    )) {
    156156                    xmlenc.writeObject(model);
    157                     xmlenc.close();
    158157                } catch (FileNotFoundException ex) {
    159158                    Main.warn("unable to write dialog layout: "+ex);
     
    163162        super.setVisible(visible);
    164163    }
    165 
    166164
    167165    private Command createCommand(Collection<OsmPrimitive> selPrim) {
     
    198196
    199197        multiSplitPane = new MultiSplitPane();
    200         try {
    201             File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml");
    202             XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(f)));
     198        File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml");
     199        try (XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream(f)))) {
    203200            Node model = (Node) decoder.readObject();
    204             decoder.close();
    205201            multiSplitPane.getMultiSplitLayout().setModel(model);
    206202            multiSplitPane.getMultiSplitLayout().setFloatingDividers(false);
    207         }
    208         catch (Exception ex) {
     203        } catch (Exception ex) {
    209204            Node modelRoot = MultiSplitLayout.parseModel(layoutDef);
    210205            multiSplitPane.getMultiSplitLayout().setModel(modelRoot);
     
    225220        info.setBackground(this.getBackground());
    226221        info.addHyperlinkListener(new HyperlinkListener() {
    227             public void hyperlinkUpdate(HyperlinkEvent e) {
     222            @Override
     223                        public void hyperlinkUpdate(HyperlinkEvent e) {
    228224                if (e == null || e.getURL() == null)
    229225                    return;
    230                 System.out.println(e.getURL());
    231226                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
    232227                    OpenBrowser.displayUrl(e.getURL().toString());
     
    472467                        }
    473468                        class TFDocumentListener implements DocumentListener {
    474                             public void insertUpdate(DocumentEvent e) {
     469                            @Override
     470                                                        public void insertUpdate(DocumentEvent e) {
    475471                                update();
    476472                            }
    477473
    478                             public void removeUpdate(DocumentEvent e) {
     474                            @Override
     475                                                        public void removeUpdate(DocumentEvent e) {
    479476                                update();
    480477                            }
    481478
    482                             public void changedUpdate(DocumentEvent e) {
     479                            @Override
     480                                                        public void changedUpdate(DocumentEvent e) {
    483481                                update();
    484482                            }
     
    540538        String[][] data = {{}};
    541539        previewTable = new JTable(data, columnNames) {
    542             public String getToolTipText(MouseEvent e) {
     540            @Override
     541                        public String getToolTipText(MouseEvent e) {
    543542                int rowIndex = rowAtPoint(e.getPoint());
    544543                int colIndex = columnAtPoint(e.getPoint());
     
    564563        addTrafficSignTag.setSelected(Main.pref.getBoolean("plugin.roadsigns.addTrafficSignTag"));
    565564        addTrafficSignTag.addActionListener(new ActionListener() {
    566             public void actionPerformed(ActionEvent e) {
     565            @Override
     566                        public void actionPerformed(ActionEvent e) {
    567567                previewModel.update();
    568568            }
     
    581581        String[] header = {tr("Key"), tr("Value")};
    582582
    583         public int getRowCount() {
     583        @Override
     584                public int getRowCount() {
    584585            return keys.size();
    585586        }
    586587
    587         public int getColumnCount() {
     588        @Override
     589                public int getColumnCount() {
    588590            return 2;
    589591        }
    590592
    591         public Object getValueAt(int rowIndex, int columnIndex) {
     593        @Override
     594                public Object getValueAt(int rowIndex, int columnIndex) {
    592595            if (columnIndex == 0) {
    593596                return keys.get(rowIndex);
     
    758761            /* scroll up again */
    759762            SwingUtilities.invokeLater(new Runnable(){
    760                 public void run() {
     763                @Override
     764                                public void run() {
    761765                    scrollInfo.getVerticalScrollBar().setValue(0);
    762766                }
     
    818822        }
    819823
    820         public Dimension getPreferredScrollableViewportSize() {
     824        @Override
     825                public Dimension getPreferredScrollableViewportSize() {
    821826            return super.getPreferredSize();
    822827        }
    823828
    824         public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction ) {
     829        @Override
     830                public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction ) {
    825831            final int FRAC = 20;
    826832            int inc = (orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth()) / FRAC;
     
    828834        }
    829835
    830         public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction ) {
     836        @Override
     837                public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction ) {
    831838            return orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth();
    832839        }
    833840
    834         public boolean getScrollableTracksViewportWidth() {
     841        @Override
     842                public boolean getScrollableTracksViewportWidth() {
    835843            return true;
    836844        }
    837845
    838         public boolean getScrollableTracksViewportHeight() {
     846        @Override
     847                public boolean getScrollableTracksViewportHeight() {
    839848            return false;
    840849        }
  • applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsPlugin.java

    r30737 r30738  
    2424import javax.swing.JOptionPane;
    2525
    26 import org.xml.sax.SAXException;
    2726import org.openstreetmap.josm.Main;
    2827import org.openstreetmap.josm.actions.JosmAction;
     
    3635import org.openstreetmap.josm.tools.Shortcut;
    3736import org.openstreetmap.josm.tools.Utils;
     37import org.xml.sax.SAXException;
    3838
    3939public class RoadSignsPlugin extends Plugin {
     
    7979        }
    8080
    81         public void actionPerformed(ActionEvent e) {
     81        @Override
     82                public void actionPerformed(ActionEvent e) {
    8283            String code = Main.pref.get("plugin.roadsigns.preset.selection", null);
    8384            if (code == null) {
     
    241242     * Returns an inputstream from urls, files and classloaders, depending on the name.
    242243     */
    243     public static InputStream getInputStream(String source) throws IOException {
     244    @SuppressWarnings("resource")
     245        public static InputStream getInputStream(String source) throws IOException {
    244246        InputStream in = null;
    245247        if (source.startsWith("http://") || source.startsWith("https://") || source.startsWith("ftp://")) {
  • applications/editors/josm/plugins/routes/.settings/org.eclipse.jdt.ui.prefs

    r19532 r30738  
    1 #Fri Jan 15 16:11:57 CET 2010
    21eclipse.preferences.version=1
    32editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
     
    98sp_cleanup.add_missing_nls_tags=false
    109sp_cleanup.add_missing_override_annotations=false
     10sp_cleanup.add_missing_override_annotations_interface_methods=false
    1111sp_cleanup.add_serial_version_id=false
    1212sp_cleanup.always_use_blocks=true
     
    1414sp_cleanup.always_use_this_for_non_static_field_access=false
    1515sp_cleanup.always_use_this_for_non_static_method_access=false
     16sp_cleanup.convert_functional_interfaces=false
    1617sp_cleanup.convert_to_enhanced_for_loop=false
    17 sp_cleanup.correct_indentation=true
     18sp_cleanup.correct_indentation=false
    1819sp_cleanup.format_source_code=false
    1920sp_cleanup.format_source_code_changes_only=false
     21sp_cleanup.insert_inferred_type_arguments=false
    2022sp_cleanup.make_local_variable_final=false
    2123sp_cleanup.make_parameters_final=false
     
    3335sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
    3436sp_cleanup.remove_private_constructors=true
     37sp_cleanup.remove_redundant_type_arguments=false
    3538sp_cleanup.remove_trailing_whitespaces=true
    3639sp_cleanup.remove_trailing_whitespaces_all=true
     
    4649sp_cleanup.sort_members=false
    4750sp_cleanup.sort_members_all=false
     51sp_cleanup.use_anonymous_class_creation=false
    4852sp_cleanup.use_blocks=false
    4953sp_cleanup.use_blocks_only_for_return_and_throw=false
     54sp_cleanup.use_lambda=false
    5055sp_cleanup.use_parentheses_in_expressions=false
    5156sp_cleanup.use_this_for_non_static_field_access=false
     
    5358sp_cleanup.use_this_for_non_static_method_access=false
    5459sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
     60sp_cleanup.use_type_arguments=false
  • applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/RoutesPlugin.java

    r30737 r30738  
    1919import org.openstreetmap.josm.gui.layer.Layer;
    2020import org.openstreetmap.josm.gui.layer.OsmDataLayer;
    21 
    2221import org.openstreetmap.josm.plugins.Plugin;
    2322import org.openstreetmap.josm.plugins.PluginInformation;
     
    3635        File routesFile = new File(getPluginDir() + File.separator + "routes.xml");
    3736        if (!routesFile.exists()) {
    38             System.out.println("File with route definitions doesn't exist, using default");
     37            Main.info("File with route definitions doesn't exist, using default");
    3938
    4039            try {
    4140                routesFile.getParentFile().mkdir();
    42                 OutputStream outputStream = new FileOutputStream(routesFile);
    43                 InputStream inputStream = Routes.class.getResourceAsStream("routes.xml");
    44 
    45                 byte[] b = new byte[512];
    46                 int read;
    47                 while ((read = inputStream.read(b)) != -1) {
    48                     outputStream.write(b, 0, read);
     41                try (
     42                    OutputStream outputStream = new FileOutputStream(routesFile);
     43                    InputStream inputStream = Routes.class.getResourceAsStream("routes.xml");
     44                ) {
     45                    byte[] b = new byte[512];
     46                    int read;
     47                    while ((read = inputStream.read(b)) != -1) {
     48                        outputStream.write(b, 0, read);
     49                    }
    4950                }
    50 
    51                 outputStream.close();
    52                 inputStream.close();
    53 
    5451            } catch (IOException e) {
    55                 e.printStackTrace();
     52                Main.error(e);
    5653            }
    5754        }
     
    6259            Unmarshaller unmarshaller = context.createUnmarshaller();
    6360            Routes routes = (Routes)unmarshaller.unmarshal(
    64                 new FileInputStream(getPluginDir() + File.separator + "routes.xml"));
     61                    new FileInputStream(getPluginDir() + File.separator + "routes.xml"));
    6562            for (RoutesXMLLayer layer:routes.getLayer()) {
    6663                if (layer.isEnabled()) {
     
    7774
    7875    public void activeLayerChange(Layer oldLayer, Layer newLayer) {
    79         // TODO Auto-generated method stub
     76        // Do nothing
    8077    }
    8178
     
    117114        checkLayers();
    118115    }
    119 
    120116}
  • applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/paint/AbstractLinePainter.java

    r23422 r30738  
    1717public abstract class AbstractLinePainter implements PathPainter {
    1818
    19         // Following two method copied from http://blog.persistent.info/2004/03/java-lineline-intersections.html
    20         protected boolean getLineLineIntersection(Line2D.Double l1,
    21                         Line2D.Double l2,
    22                         Point intersection)
    23         {
    24                 double  x1 = l1.getX1(), y1 = l1.getY1(),
    25                 x2 = l1.getX2(), y2 = l1.getY2(),
    26                 x3 = l2.getX1(), y3 = l2.getY1(),
    27                 x4 = l2.getX2(), y4 = l2.getY2();
    28                 double dx1 = x2 - x1;
    29                 double dx2 = x4 - x3;
    30                 double dy1 = y2 - y1;
    31                 double dy2 = y4 - y3;
     19    // Following two method copied from http://blog.persistent.info/2004/03/java-lineline-intersections.html
     20    protected boolean getLineLineIntersection(Line2D.Double l1,
     21            Line2D.Double l2,
     22            Point intersection)
     23    {
     24        double  x1 = l1.getX1(), y1 = l1.getY1(),
     25        x2 = l1.getX2(), y2 = l1.getY2(),
     26        x3 = l2.getX1(), y3 = l2.getY1(),
     27        x4 = l2.getX2(), y4 = l2.getY2();
     28        double dx1 = x2 - x1;
     29        double dx2 = x4 - x3;
     30        double dy1 = y2 - y1;
     31        double dy2 = y4 - y3;
    3232
    33                 double ua = (dx2 * (y1 - y3) - dy2 * (x1 - x3)) / (dy2 * dx1 - dx2 * dy1);
     33        double ua = (dx2 * (y1 - y3) - dy2 * (x1 - x3)) / (dy2 * dx1 - dx2 * dy1);
    3434
    35                 if (Math.abs(dy2 * dx1 - dx2 * dy1) < 0.0001) {
    36                         intersection.x = (int)l1.x2;
    37                         intersection.y = (int)l1.y2;
    38                         return false;
    39                 } else {
    40                         intersection.x = (int)(x1 + ua * (x2 - x1));
    41                         intersection.y = (int)(y1 + ua * (y2 - y1));
    42                 }
     35        if (Math.abs(dy2 * dx1 - dx2 * dy1) < 0.0001) {
     36            intersection.x = (int)l1.x2;
     37            intersection.y = (int)l1.y2;
     38            return false;
     39        } else {
     40            intersection.x = (int)(x1 + ua * (x2 - x1));
     41            intersection.y = (int)(y1 + ua * (y2 - y1));
     42        }
    4343
    44                 return true;
    45         }
     44        return true;
     45    }
    4646
    47         protected double det(double a, double b, double c, double d)
    48         {
    49                 return a * d - b * c;
    50         }
     47    protected double det(double a, double b, double c, double d)
     48    {
     49        return a * d - b * c;
     50    }
    5151
    52         protected Point shiftPoint(Point2D p1, Point2D p2, double shift) {
    53                 double dx = p2.getX() - p1.getX();
    54                 double dy = p2.getY() - p1.getY();
     52    protected Point shiftPoint(Point2D p1, Point2D p2, double shift) {
     53        double dx = p2.getX() - p1.getX();
     54        double dy = p2.getY() - p1.getY();
    5555
    56                 // Perpendicular vector
    57                 double ndx = -dy;
    58                 double ndy = dx;
     56        // Perpendicular vector
     57        double ndx = -dy;
     58        double ndy = dx;
    5959
    60                 // Normalize
    61                 double length = Math.sqrt(ndx * ndx + ndy * ndy);
    62                 ndx = ndx / length;
    63                 ndy = ndy / length;
     60        // Normalize
     61        double length = Math.sqrt(ndx * ndx + ndy * ndy);
     62        ndx = ndx / length;
     63        ndy = ndy / length;
    6464
    65                 return new Point((int)(p1.getX() + shift * ndx), (int)(p1.getY() + shift * ndy));
    66         }
     65        return new Point((int)(p1.getX() + shift * ndx), (int)(p1.getY() + shift * ndy));
     66    }
    6767
    68         protected Line2D.Double shiftLine(Point2D p1, Point2D p2, double shift) {
    69                 double dx = p2.getX() - p1.getX();
    70                 double dy = p2.getY() - p1.getY();
     68    protected Line2D.Double shiftLine(Point2D p1, Point2D p2, double shift) {
     69        double dx = p2.getX() - p1.getX();
     70        double dy = p2.getY() - p1.getY();
    7171
    72                 Point2D point1 = shiftPoint(p1, p2, shift);
    73                 Point2D point2 = new Point2D.Double(point1.getX() + dx, point1.getY() + dy);
     72        Point2D point1 = shiftPoint(p1, p2, shift);
     73        Point2D point2 = new Point2D.Double(point1.getX() + dx, point1.getY() + dy);
    7474
    75                 return new Line2D.Double(
    76                                 point1, point2);
    77         }
     75        return new Line2D.Double(
     76                point1, point2);
     77    }
    7878
    79         protected GeneralPath getPath(Graphics2D g, MapView mapView, List<Node> nodes, double shift) {
     79    protected GeneralPath getPath(Graphics2D g, MapView mapView, List<Node> nodes, double shift) {
    8080
    81                 GeneralPath path = new GeneralPath();
     81        GeneralPath path = new GeneralPath();
    8282
    83                 if (nodes.size() < 2) {
    84                         return path;
    85                 }
     83        if (nodes.size() < 2) {
     84            return path;
     85        }
    8686
    87                 Point p1 = null;
    88                 Point p2 = null;
    89                 Point p3 = null;
    90                 Point lastPoint = null;
     87        Point p1 = null;
     88        Point p2 = null;
     89        Point p3 = null;
     90        Point lastPoint = null;
    9191
    92                 for (Node n: nodes) {
    93                         Point p = mapView.getPoint(n);
     92        for (Node n: nodes) {
     93            Point p = mapView.getPoint(n);
    9494
    95                         if (!p.equals(p3)) {
    96                                 p1 = p2;
    97                                 p2 = p3;
    98                                 p3 = p;
    99                         } else {
    100                                 continue;
    101                         }
     95            if (!p.equals(p3)) {
     96                p1 = p2;
     97                p2 = p3;
     98                p3 = p;
     99            } else {
     100                continue;
     101            }
    102102
    103                         p = null;
    104                         if (p2 != null) {
    105                                 if (p1 == null) {
    106                                         p = shiftPoint(p2, p3, shift);
    107                                 } else {
    108                                         Line2D.Double line1 = shiftLine(p1, p2, shift);
    109                                         Line2D.Double line2 = shiftLine(p2, p3, shift);
     103            p = null;
     104            if (p2 != null) {
     105                if (p1 == null) {
     106                    p = shiftPoint(p2, p3, shift);
     107                } else {
     108                    Line2D.Double line1 = shiftLine(p1, p2, shift);
     109                    Line2D.Double line2 = shiftLine(p2, p3, shift);
    110110
    111                                         /*path.moveTo((float)line1.x1, (float)line1.y1);
     111                    /*path.moveTo((float)line1.x1, (float)line1.y1);
    112112                    path.lineTo((float)line1.x2, (float)line1.y2);
    113113                    path.moveTo((float)line2.x1, (float)line2.y1);
    114114                    path.lineTo((float)line2.x2, (float)line2.y2);*/
    115115
    116                                         p = new Point();
    117                                         if (!getLineLineIntersection(line1, line2, p)) {
    118                                                 p = null;
    119                                         } else {
    120                                                 int dx = p.x - p2.x;
    121                                                 int dy = p.y - p2.y;
    122                                                 int distance = (int)Math.sqrt(dx * dx + dy * dy);
    123                                                 if (distance > 10) {
    124                                                         p.x = p2.x + dx / (distance / 10);
    125                                                         p.y = p2.y + dy / (distance / 10);
    126                                                 }
    127                                         }
    128                                 }
    129                         }
     116                    p = new Point();
     117                    if (!getLineLineIntersection(line1, line2, p)) {
     118                        p = null;
     119                    } else {
     120                        int dx = p.x - p2.x;
     121                        int dy = p.y - p2.y;
     122                        int distance = (int)Math.sqrt(dx * dx + dy * dy);
     123                        if (distance > 10) {
     124                            p.x = p2.x + dx / (distance / 10);
     125                            p.y = p2.y + dy / (distance / 10);
     126                        }
     127                    }
     128                }
     129            }
    130130
    131                         if (p != null && lastPoint != null) {
    132                                 drawSegment(g, mapView, path, lastPoint, p);
    133                         }
    134                         if (p != null) {
    135                                 lastPoint = p;
    136                         }
    137                 }
     131            if (p != null && lastPoint != null) {
     132                drawSegment(g, mapView, path, lastPoint, p);
     133            }
     134            if (p != null) {
     135                lastPoint = p;
     136            }
     137        }
    138138
    139                 if (p2 != null && p3 != null && lastPoint != null) {
    140                         p3 = shiftPoint(p3, p2, -shift);
    141                         drawSegment(g, mapView, path, lastPoint, p3);
    142                 }
     139        if (p2 != null && p3 != null && lastPoint != null) {
     140            p3 = shiftPoint(p3, p2, -shift);
     141            drawSegment(g, mapView, path, lastPoint, p3);
     142        }
    143143
    144                 return path;
    145         }
     144        return path;
     145    }
    146146
    147         private void drawSegment(Graphics2D g, NavigatableComponent nc, GeneralPath path, Point p1, Point p2) {
    148                 boolean drawIt = false;
    149                 if (Main.isOpenjdk) {
    150                         /**
    151                         * Work around openjdk bug. It leads to drawing artefacts when zooming in a lot. (#4289, #4424)
    152                         * (It looks like int overflow when clipping.) We do custom clipping.
    153                         */
    154                         Rectangle bounds = g.getClipBounds();
    155                         bounds.grow(100, 100);                  // avoid arrow heads at the border
    156                         LineClip clip = new LineClip(p1, p2, bounds);
    157                         drawIt = clip.execute();
    158                         if (drawIt) {
    159                                 p1 = clip.getP1();
    160                                 p2 = clip.getP2();
    161                         }
    162                 } else {
    163                         drawIt = isSegmentVisible(nc, p1, p2);
    164                 }
    165                 if (drawIt) {
    166                         /* draw segment line */
    167                         path.moveTo(p1.x, p1.y);
    168                         path.lineTo(p2.x, p2.y);
    169                 }
    170         }
     147    private void drawSegment(Graphics2D g, NavigatableComponent nc, GeneralPath path, Point p1, Point p2) {
     148        boolean drawIt = false;
     149        if (Main.isOpenjdk) {
     150            /**
     151            * Work around openjdk bug. It leads to drawing artefacts when zooming in a lot. (#4289, #4424)
     152            * (It looks like int overflow when clipping.) We do custom clipping.
     153            */
     154            Rectangle bounds = g.getClipBounds();
     155            bounds.grow(100, 100);                  // avoid arrow heads at the border
     156            LineClip clip = new LineClip(p1, p2, bounds);
     157            drawIt = clip.execute();
     158            if (drawIt) {
     159                p1 = clip.getP1();
     160                p2 = clip.getP2();
     161            }
     162        } else {
     163            drawIt = isSegmentVisible(nc, p1, p2);
     164        }
     165        if (drawIt) {
     166            /* draw segment line */
     167            path.moveTo(p1.x, p1.y);
     168            path.lineTo(p2.x, p2.y);
     169        }
     170    }
    171171
    172         private boolean isSegmentVisible(NavigatableComponent nc, Point p1, Point p2) {
    173                 if ((p1.x < 0) && (p2.x < 0)) return false;
    174                 if ((p1.y < 0) && (p2.y < 0)) return false;
    175                 if ((p1.x > nc.getWidth()) && (p2.x > nc.getWidth())) return false;
    176                 if ((p1.y > nc.getHeight()) && (p2.y > nc.getHeight())) return false;
    177                 return true;
    178         }
     172    private boolean isSegmentVisible(NavigatableComponent nc, Point p1, Point p2) {
     173        if ((p1.x < 0) && (p2.x < 0)) return false;
     174        if ((p1.y < 0) && (p2.y < 0)) return false;
     175        if ((p1.x > nc.getWidth()) && (p2.x > nc.getWidth())) return false;
     176        if ((p1.y > nc.getHeight()) && (p2.y > nc.getHeight())) return false;
     177        return true;
     178    }
    179179
    180180
  • applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xml

    r19345 r30738  
    22<routes xmlns="http://www.example.org/routes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/routes routes.xsd ">
    33<!-- pattern is the same pattern as used in SearchAction -->
    4         <layer name="Czech hiking trails">
    5                 <route color="#FF0000">
    6                         <pattern>
    7                         ((type:relation | type:way) kct_red=*) | (color=red type=route route=hiking network="cz:kct")
    8                         </pattern>
    9                 </route>
    10                 <route color="#FFFF00">
    11                         <pattern>
    12                         ((type:relation | type:way) kct_yellow=*) | (color=yellow type=route route=hiking network="cz:kct")
    13                         </pattern>                     
    14                 </route>
    15                 <route color="#0000FF">
    16                         <pattern>
    17                         ((type:relation | type:way) kct_blue=*) | (color=blue type=route route=hiking network="cz:kct")
    18                         </pattern>
    19                 </route>
    20                 <route color="#00FF00">
    21                         <pattern>
    22                         ((type:relation | type:way) kct_green=*) | (color=green type=route route=hiking network="cz:kct")
    23                         </pattern>             
    24                 </route>
    25         </layer>
    26         <layer name="Cycle routes">
    27                 <route color="#FF00FF">
    28                         <pattern>
    29                         (type:way (ncn=* | (lcn=* | rcn=* ))) | (type:relation type=route route=bicycle)
    30                         </pattern>
    31                 </route>
    32         </layer>
     4    <layer name="Czech hiking trails">
     5        <route color="#FF0000">
     6            <pattern>
     7            ((type:relation | type:way) kct_red=*) | (color=red type=route route=hiking network="cz:kct")
     8            </pattern>
     9        </route>
     10        <route color="#FFFF00">
     11            <pattern>
     12            ((type:relation | type:way) kct_yellow=*) | (color=yellow type=route route=hiking network="cz:kct")
     13            </pattern>           
     14        </route>
     15        <route color="#0000FF">
     16            <pattern>
     17            ((type:relation | type:way) kct_blue=*) | (color=blue type=route route=hiking network="cz:kct")
     18            </pattern>
     19        </route>
     20        <route color="#00FF00">
     21            <pattern>
     22            ((type:relation | type:way) kct_green=*) | (color=green type=route route=hiking network="cz:kct")
     23            </pattern>       
     24        </route>
     25    </layer>
     26    <layer name="Cycle routes">
     27        <route color="#FF00FF">
     28            <pattern>
     29            (type:way (ncn=* | (lcn=* | rcn=* ))) | (type:relation type=route route=bicycle)
     30            </pattern>
     31        </route>
     32    </layer>
    3333</routes>
  • applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xsd

    r16593 r30738  
    1111
    1212<annotation>
    13         <appinfo>
    14                 <jxb:schemaBindings>   
    15                         <jxb:nameXmlTransform>
    16                                 <jxb:typeName prefix="RoutesXML"/>
    17                         </jxb:nameXmlTransform>
    18                 </jxb:schemaBindings>
    19         </appinfo>
     13    <appinfo>
     14        <jxb:schemaBindings>   
     15            <jxb:nameXmlTransform>
     16                <jxb:typeName prefix="RoutesXML"/>
     17            </jxb:nameXmlTransform>
     18        </jxb:schemaBindings>
     19    </appinfo>
    2020</annotation>
    2121
    2222<element name="routes">
    23         <complexType>
    24                 <sequence>
    25                         <element name="layer" type="tns:layer" minOccurs="0" maxOccurs="unbounded"/>
    26                 </sequence>
    27         </complexType>
     23    <complexType>
     24        <sequence>
     25            <element name="layer" type="tns:layer" minOccurs="0" maxOccurs="unbounded"/>
     26        </sequence>
     27    </complexType>
    2828</element>
    2929
    3030<complexType name="layer">
    31         <sequence>
    32                 <element name="route" type="tns:route" minOccurs="0" maxOccurs="unbounded"/>
    33         </sequence>
    34         <attribute name="name" type="string"/>
    35         <attribute name="enabled" type="boolean" default="true"/>
     31    <sequence>
     32        <element name="route" type="tns:route" minOccurs="0" maxOccurs="unbounded"/>
     33    </sequence>
     34    <attribute name="name" type="string"/>
     35    <attribute name="enabled" type="boolean" default="true"/>
    3636</complexType>
    3737
    3838<complexType name="route">
    39         <sequence>
    40                 <element name="pattern" type="string"/>         
    41         </sequence>
    42         <attribute name="color" type="string"/>
    43         <attribute name="enabled" type="boolean" default="true"/>
     39    <sequence>
     40        <element name="pattern" type="string"/>       
     41    </sequence>
     42    <attribute name="color" type="string"/>
     43    <attribute name="enabled" type="boolean" default="true"/>
    4444</complexType>
    4545
  • applications/editors/josm/plugins/sds/.settings/org.eclipse.jdt.core.prefs

    r30736 r30738  
    4040org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
    4141org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
    42 org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
     42org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore
    4343org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
    4444org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/DetermineSdsModificationsUploadHook.java

    r30737 r30738  
    3232public class DetermineSdsModificationsUploadHook implements UploadHook
    3333{
    34         private SeparateDataStorePlugin plugin;
     34    private SeparateDataStorePlugin plugin;
    3535
    36         DetermineSdsModificationsUploadHook(SeparateDataStorePlugin plugin)     {
    37                 this.plugin = plugin;
    38         }
    39        
     36    DetermineSdsModificationsUploadHook(SeparateDataStorePlugin plugin)    {
     37        this.plugin = plugin;
     38    }
     39   
    4040    public boolean checkUpload(APIDataSet apiDataSet) {
    41        
    42         ArrayList<OsmPrimitive> droplist = new ArrayList<>();
    43        
    44         // check deleted primitives for special tags.
    45         for (OsmPrimitive del : apiDataSet.getPrimitivesToDelete()) {
    46                 IPrimitive old = plugin.getOriginalPrimitive(del);
    47                 if (hasSpecialTags(old)) {
    48                         // request deletion of all tags for this object on special server.
    49                         plugin.enqueueForUpload(del, new HashMap<String, String>(), false);
    50                 }
    51         }
     41       
     42        ArrayList<OsmPrimitive> droplist = new ArrayList<>();
     43       
     44        // check deleted primitives for special tags.
     45        for (OsmPrimitive del : apiDataSet.getPrimitivesToDelete()) {
     46            IPrimitive old = plugin.getOriginalPrimitive(del);
     47            if (hasSpecialTags(old)) {
     48                // request deletion of all tags for this object on special server.
     49                plugin.enqueueForUpload(del, new HashMap<String, String>(), false);
     50            }
     51        }
    5252
    53         // check modified primitives.
    54         for (OsmPrimitive upd : apiDataSet.getPrimitivesToUpdate()) {
    55                 
    56                 HashSet<String> allKeys = new HashSet<>();
    57                 boolean specialTags = false;
    58                 
    59                 // process tags of new object
    60                 for (String key : upd.keySet()) {
    61                         allKeys.add(key);
    62                         if (!specialTags && isSpecialKey(key)) specialTags = true;
    63                 }
    64                 
    65                 // process tags of old object
    66                 IPrimitive old = plugin.getOriginalPrimitive(upd);
    67                 for (String key : old.keySet()) {
    68                         allKeys.add(key);
    69                         if (!specialTags && isSpecialKey(key)) specialTags = true;
    70                 }
     53        // check modified primitives.
     54           for (OsmPrimitive upd : apiDataSet.getPrimitivesToUpdate()) {
     55              
     56               HashSet<String> allKeys = new HashSet<>();
     57               boolean specialTags = false;
     58              
     59               // process tags of new object
     60               for (String key : upd.keySet()) {
     61                   allKeys.add(key);
     62                   if (!specialTags && isSpecialKey(key)) specialTags = true;
     63               }
     64              
     65               // process tags of old object
     66               IPrimitive old = plugin.getOriginalPrimitive(upd);
     67               for (String key : old.keySet()) {
     68                   allKeys.add(key);
     69                  if (!specialTags && isSpecialKey(key)) specialTags = true;
     70               }
    7171
    72                 // if neither has special tags, done with this object.
    73                 if (!specialTags) continue;
    74                 
    75                 // special tags are involved. find out what, exactly, has changed.
    76                 boolean changeInSpecialTags = false;
    77                 boolean changeInOtherTags = false;
    78                 for (String key : allKeys) {
    79                         if (old.get(key) == null || upd.get(key) == null || !old.get(key).equals(upd.get(key))) {
    80                                 if (isSpecialKey(key)) changeInSpecialTags = true; else changeInOtherTags = true;
    81                                 if (changeInSpecialTags && changeInOtherTags) break;
    82                         }
    83                 }
    84                 
    85                 // change *only* in standard tags - done with this object.
    86                 if (!changeInSpecialTags) continue;
    87                 
    88                 // assemble new set of special tags. might turn out to be empty.
    89                 HashMap<String, String> newSpecialTags = new HashMap<>();
    90                 for (String key : upd.keySet()) {
    91                         if (isSpecialKey(key)) newSpecialTags.put(key, upd.get(key));
    92                 }
    93                 
    94                 boolean uploadToOsm = changeInOtherTags;
    95                 
    96                 // not done yet: if no changes in standard tags, we need to find out if
    97                 // there were changes in the other properties (node: lat/lon, way/relation:
    98                 // member list). If the answer is no, then the object must be removed from
    99                 // JOSM's normal upload queue, else we would be uploading a non-edit.
    100                 if (!changeInOtherTags) {
    101                         switch(old.getType()) {
    102                         case NODE:
    103                                 INode nold = (INode) old;
    104                                 INode nupd = (INode) upd;
    105                                 uploadToOsm = !(nold.getCoor().equals(nupd.getCoor()));
    106                                 break;
    107                         case WAY:
    108                                 IWay wold = (IWay) old;
    109                                 IWay wupd = (IWay) upd;
    110                                 if (wold.getNodesCount() != wupd.getNodesCount()) {
    111                                         uploadToOsm = true;
    112                                         break;
    113                                 }
    114                                 for (int i = 0; i < wold.getNodesCount(); i++) {
    115                                         if (wold.getNodeId(i) != wupd.getNodeId(i)) {
    116                                                 uploadToOsm = true;
    117                                                 break;
    118                                         }
    119                                 }
    120                                 break;
    121                         case RELATION:
    122                                 IRelation rold = (IRelation) old;
    123                                 IRelation rupd = (IRelation) upd;
    124                                 if (rold.getMembersCount()!= rupd.getMembersCount()) {
    125                                         uploadToOsm = true;
    126                                         break;
    127                                 }
    128                                 for (int i = 0; i < rold.getMembersCount(); i++) {
    129                                         if (rold.getMemberType(i) != rupd.getMemberType(i) ||
    130                                                 rold.getMemberId(i) != rupd.getMemberId(i)) {
    131                                                 uploadToOsm = true;
    132                                                 break;
    133                                         }
    134                                 }
    135                                 break;
    136                         }
    137                 }
    138                 
    139                 // request that new set of special tags be uploaded
    140                 plugin.enqueueForUpload(upd, newSpecialTags, !uploadToOsm);
    141                 
    142                 // we cannot remove from getPrimitivesToUpdate, this would result in a
    143                 // ConcurrentModificationException.
    144                 if (!uploadToOsm) droplist.add(upd);
    145                 
    146         }
    147         
    148         apiDataSet.getPrimitivesToUpdate().removeAll(droplist);
    149                         
    150         // check added primitives.
    151         for (OsmPrimitive add : apiDataSet.getPrimitivesToAdd()) {
    152                 // assemble new set of special tags. might turn out to be empty.
    153                 HashMap<String, String> newSpecialTags = new HashMap<>();
    154                 for (String key : add.keySet()) {
    155                         if (isSpecialKey(key)) newSpecialTags.put(key, add.get(key));
    156                 }
    157                 if (!newSpecialTags.isEmpty()) plugin.enqueueForUpload(add, newSpecialTags, false);
    158         }
    159        
    160         // FIXME it is possible that the list of OSM edits is totally empty.
    161                 return true;
     72               // if neither has special tags, done with this object.
     73               if (!specialTags) continue;
     74              
     75               // special tags are involved. find out what, exactly, has changed.
     76               boolean changeInSpecialTags = false;
     77               boolean changeInOtherTags = false;
     78               for (String key : allKeys) {
     79                   if (old.get(key) == null || upd.get(key) == null || !old.get(key).equals(upd.get(key))) {
     80                       if (isSpecialKey(key)) changeInSpecialTags = true; else changeInOtherTags = true;
     81                       if (changeInSpecialTags && changeInOtherTags) break;
     82                   }
     83               }
     84              
     85               // change *only* in standard tags - done with this object.
     86               if (!changeInSpecialTags) continue;
     87              
     88               // assemble new set of special tags. might turn out to be empty.
     89               HashMap<String, String> newSpecialTags = new HashMap<>();
     90               for (String key : upd.keySet()) {
     91                   if (isSpecialKey(key)) newSpecialTags.put(key, upd.get(key));
     92               }
     93              
     94               boolean uploadToOsm = changeInOtherTags;
     95              
     96               // not done yet: if no changes in standard tags, we need to find out if
     97               // there were changes in the other properties (node: lat/lon, way/relation:
     98               // member list). If the answer is no, then the object must be removed from
     99               // JOSM's normal upload queue, else we would be uploading a non-edit.
     100               if (!changeInOtherTags) {
     101                   switch(old.getType()) {
     102                   case NODE:
     103                       INode nold = (INode) old;
     104                       INode nupd = (INode) upd;
     105                       uploadToOsm = !(nold.getCoor().equals(nupd.getCoor()));
     106                       break;
     107                   case WAY:
     108                       IWay wold = (IWay) old;
     109                       IWay wupd = (IWay) upd;
     110                       if (wold.getNodesCount() != wupd.getNodesCount()) {
     111                           uploadToOsm = true;
     112                           break;
     113                       }
     114                       for (int i = 0; i < wold.getNodesCount(); i++) {
     115                           if (wold.getNodeId(i) != wupd.getNodeId(i)) {
     116                               uploadToOsm = true;
     117                               break;
     118                           }
     119                       }
     120                       break;
     121                   case RELATION:
     122                       IRelation rold = (IRelation) old;
     123                       IRelation rupd = (IRelation) upd;
     124                       if (rold.getMembersCount()!= rupd.getMembersCount()) {
     125                           uploadToOsm = true;
     126                           break;
     127                       }
     128                       for (int i = 0; i < rold.getMembersCount(); i++) {
     129                           if (rold.getMemberType(i) != rupd.getMemberType(i) ||
     130                               rold.getMemberId(i) != rupd.getMemberId(i)) {
     131                               uploadToOsm = true;
     132                               break;
     133                           }
     134                       }
     135                       break;
     136                   }
     137               }
     138              
     139               // request that new set of special tags be uploaded
     140               plugin.enqueueForUpload(upd, newSpecialTags, !uploadToOsm);
     141              
     142               // we cannot remove from getPrimitivesToUpdate, this would result in a
     143               // ConcurrentModificationException.
     144               if (!uploadToOsm) droplist.add(upd);
     145              
     146        }
     147          
     148        apiDataSet.getPrimitivesToUpdate().removeAll(droplist);
     149                  
     150           // check added primitives.
     151           for (OsmPrimitive add : apiDataSet.getPrimitivesToAdd()) {
     152               // assemble new set of special tags. might turn out to be empty.
     153               HashMap<String, String> newSpecialTags = new HashMap<>();
     154               for (String key : add.keySet()) {
     155                   if (isSpecialKey(key)) newSpecialTags.put(key, add.get(key));
     156               }
     157               if (!newSpecialTags.isEmpty()) plugin.enqueueForUpload(add, newSpecialTags, false);
     158        }
     159       
     160           // FIXME it is possible that the list of OSM edits is totally empty.
     161        return true;
    162162
    163163    }
    164164   
    165165    boolean hasSpecialTags(IPrimitive p) {
    166         for (String key : p.keySet()) {
    167                 if (isSpecialKey(key)) return true;
    168         }   
    169         return false;
     166        for (String key : p.keySet()) {
     167            if (isSpecialKey(key)) return true;
     168        }   
     169        return false;
    170170    }
    171171   
    172172    boolean isSpecialKey(String key) {
    173         return key.startsWith(plugin.getIgnorePrefix());
     173        return key.startsWith(plugin.getIgnorePrefix());
    174174    }
    175175}
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/ReadPostprocessor.java

    r30737 r30738  
    2424
    2525public class ReadPostprocessor implements OsmServerReadPostprocessor {
    26        
    27         private ArrayList<Long> nodeList;
    28         private ArrayList<Long> wayList;
    29         private ArrayList<Long> relationList;
    30        
    31         private SeparateDataStorePlugin plugin;
     26   
     27    private ArrayList<Long> nodeList;
     28    private ArrayList<Long> wayList;
     29    private ArrayList<Long> relationList;
     30   
     31    private SeparateDataStorePlugin plugin;
    3232
    33         public ReadPostprocessor(SeparateDataStorePlugin plugin) {
    34                 this.plugin = plugin;
    35         }
    36        
     33    public ReadPostprocessor(SeparateDataStorePlugin plugin) {
     34        this.plugin = plugin;
     35    }
     36   
    3737    @Override
    3838    public void postprocessDataSet(DataSet ds, ProgressMonitor progress) {
    3939       
    40                 nodeList = new ArrayList<>();
    41                 wayList = new ArrayList<>();
    42                 relationList = new ArrayList<>();
     40        nodeList = new ArrayList<>();
     41        wayList = new ArrayList<>();
     42        relationList = new ArrayList<>();
    4343
    44                 Visitor adder = new Visitor() {
    45                         @Override
    46                         public void visit(Node n) {
    47                                 nodeList.add(n.getId());
    48                                 plugin.originalNodes.put(n.getId(), n.save());
    49                         }
    50                         @Override
    51                         public void visit(Way w) {
    52                                 wayList.add(w.getId());
    53                                 plugin.originalWays.put(w.getId(), w.save());
    54                         }
    55                         @Override
    56                         public void visit(Relation e) {
    57                                 relationList.add(e.getId());
    58                                 plugin.originalNodes.put(e.getId(), e.save());
    59                         }
    60                         @Override
    61                         public void visit(Changeset cs) {}
    62                 };
    63                
    64                 for (OsmPrimitive p : ds.allPrimitives()) {
    65                         p.accept(adder);
    66                 }
    67                        
    68                 SdsApi api = SdsApi.getSdsApi();
    69                 String rv = "";
    70                 try {
    71                         rv = api.requestShadowsFromSds(nodeList, wayList, relationList, progress);
    72                 } catch (SdsTransferException e) {
    73                         // TODO Auto-generated catch block
    74                         e.printStackTrace();
    75                 }
    76                
    77                 // this is slightly inefficient, as we're re-making the string into
    78                 // an input stream when there was an input stream to be had inside the
    79                 // SdsApi already, but this encapsulates things better.
     44        Visitor adder = new Visitor() {
     45            @Override
     46            public void visit(Node n) {
     47                nodeList.add(n.getId());
     48                plugin.originalNodes.put(n.getId(), n.save());
     49            }
     50            @Override
     51            public void visit(Way w) {
     52                wayList.add(w.getId());
     53                plugin.originalWays.put(w.getId(), w.save());
     54            }
     55            @Override
     56            public void visit(Relation e) {
     57                relationList.add(e.getId());
     58                plugin.originalNodes.put(e.getId(), e.save());
     59            }
     60            @Override
     61            public void visit(Changeset cs) {}
     62        };
     63       
     64        for (OsmPrimitive p : ds.allPrimitives()) {
     65            p.accept(adder);
     66        }
     67           
     68        SdsApi api = SdsApi.getSdsApi();
     69        String rv = "";
     70        try {
     71            rv = api.requestShadowsFromSds(nodeList, wayList, relationList, progress);
     72        } catch (SdsTransferException e) {
     73            // TODO Auto-generated catch block
     74            e.printStackTrace();
     75        }
     76       
     77        // this is slightly inefficient, as we're re-making the string into
     78        // an input stream when there was an input stream to be had inside the
     79        // SdsApi already, but this encapsulates things better.
    8080        InputStream xmlStream;
    81                 try {
    82                         xmlStream = new ByteArrayInputStream(rv.getBytes("UTF-8"));
    83                 InputSource inputSource = new InputSource(xmlStream);
    84                         SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new SdsParser(ds, plugin));
    85                 } catch (UnsupportedEncodingException e1) {
    86                         // TODO Auto-generated catch block
    87                         e1.printStackTrace();
    88                 } catch (SAXException e) {
    89                         // TODO Auto-generated catch block
    90                         e.printStackTrace();
    91                 } catch (IOException e) {
    92                         // TODO Auto-generated catch block
    93                         e.printStackTrace();
    94                 } catch (ParserConfigurationException e) {
    95                         // TODO Auto-generated catch block
    96                         e.printStackTrace();
    97                 }
     81        try {
     82            xmlStream = new ByteArrayInputStream(rv.getBytes("UTF-8"));
     83            InputSource inputSource = new InputSource(xmlStream);
     84            SAXParserFactory.newInstance().newSAXParser().parse(inputSource, new SdsParser(ds, plugin));
     85        } catch (UnsupportedEncodingException e1) {
     86            // TODO Auto-generated catch block
     87            e1.printStackTrace();
     88        } catch (SAXException e) {
     89            // TODO Auto-generated catch block
     90            e.printStackTrace();
     91        } catch (IOException e) {
     92            // TODO Auto-generated catch block
     93            e.printStackTrace();
     94        } catch (ParserConfigurationException e) {
     95            // TODO Auto-generated catch block
     96            e.printStackTrace();
     97        }
    9898
    9999    }
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsApi.java

    r30737 r30738  
    3434 *
    3535 * This is modeled after JOSM's own OsmAPI class.
    36  * 
     36 *
    3737 */
    3838public class SdsApi extends SdsConnection {
     
    4242    /** the collection of instantiated OSM APIs */
    4343    private static HashMap<String, SdsApi> instances = new HashMap<>();
    44    
     44
    4545    /**
    4646     * replies the {@see OsmApi} for a given server URL
     
    123123     * @param osm the primitive
    124124     * @throws SdsTransferException if something goes wrong
    125      
     125
    126126    public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException {
    127127        String ret = "";
     
    144144     * @param monitor the progress monitor
    145145     * @throws SdsTransferException if something goes wrong
    146      
     146
    147147    public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException {
    148148        String ret = null;
     
    165165     * @param osm the primitive
    166166     * @throws SdsTransferException if something goes wrong
    167      
     167
    168168    public void deletePrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException {
    169169        ensureValidChangeset();
     
    182182     * @param list the list of changed OSM Primitives
    183183     * @param  monitor the progress monitor
    184      * @return 
     184     * @return
    185185     * @return list of processed primitives
    186      * @throws SdsTransferException 
     186     * @throws SdsTransferException
    187187     * @throws SdsTransferException if something is wrong
    188      
     188
    189189    public Collection<IPrimitive> uploadDiff(Collection<? extends IPrimitive> list, ProgressMonitor monitor) throws SdsTransferException {
    190190        try {
     
    227227    }
    228228    */
    229    
     229
    230230    public String requestShadowsFromSds(List<Long> nodes, List<Long> ways, List<Long> relations, ProgressMonitor pm) throws SdsTransferException {
    231        
    232         StringBuilder request = new StringBuilder();
    233         String delim = "";
    234         String comma = "";
    235        
    236         if (nodes != null && !nodes.isEmpty()) {
    237                 request.append(delim);
    238                 delim = "&";
    239                 comma = "";
    240                 request.append("nodes=");
    241                 for (long i : nodes) {
    242                         request.append(comma);
    243                         comma = ",";
    244                         request.append(i);
    245                 }
    246         }
    247         if (ways != null && !ways.isEmpty()) {
    248                 request.append(delim);
    249                 delim = "&";
    250                 comma = "";
    251                 request.append("ways=");
    252                 for (long i : ways) {
    253                         request.append(comma);
    254                         comma = ",";
    255                         request.append(i);
    256                 }
    257         }
    258         if (relations != null && !relations.isEmpty()) {
    259                 request.append(delim);
    260                 delim = "&";
    261                 comma = "";
    262                 request.append("relations=");
    263                 for (long i : relations) {
    264                         request.append(comma);
    265                         comma = ",";
    266                         request.append(i);
    267                 }
    268         }
    269        
    270         return sendRequest("POST", "collectshadows", request.toString(), pm ,true);
    271    
     231
     232        StringBuilder request = new StringBuilder();
     233        String delim = "";
     234        String comma = "";
     235
     236        if (nodes != null && !nodes.isEmpty()) {
     237            request.append(delim);
     238            delim = "&";
     239            comma = "";
     240            request.append("nodes=");
     241            for (long i : nodes) {
     242                request.append(comma);
     243                comma = ",";
     244                request.append(i);
     245            }
     246        }
     247        if (ways != null && !ways.isEmpty()) {
     248            request.append(delim);
     249            delim = "&";
     250            comma = "";
     251            request.append("ways=");
     252            for (long i : ways) {
     253                request.append(comma);
     254                comma = ",";
     255                request.append(i);
     256            }
     257        }
     258        if (relations != null && !relations.isEmpty()) {
     259            request.append(delim);
     260            delim = "&";
     261            comma = "";
     262            request.append("relations=");
     263            for (long i : relations) {
     264                request.append(comma);
     265                comma = ",";
     266                request.append(i);
     267            }
     268        }
     269
     270        return sendRequest("POST", "collectshadows", request.toString(), pm ,true);
     271
    272272    }
    273273
     
    304304        return sendRequest(requestMethod, urlSuffix, requestBody, monitor, doAuth, false);
    305305    }
    306    
     306
    307307    public boolean updateSds(String message, ProgressMonitor pm) {
    308         try {
    309                         sendRequest("POST", "createshadows", message, pm);
    310                 } catch (SdsTransferException e) {
    311                         // TODO Auto-generated catch block
    312                         e.printStackTrace();
    313                 }
    314         return true;
     308        try {
     309            sendRequest("POST", "createshadows", message, pm);
     310        } catch (SdsTransferException e) {
     311            // TODO Auto-generated catch block
     312            e.printStackTrace();
     313        }
     314        return true;
    315315    }
    316316
     
    352352                    activeConnection.setDoOutput(true);
    353353                    activeConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    354                     OutputStream out = activeConnection.getOutputStream();
    355 
    356                     // It seems that certain bits of the Ruby API are very unhappy upon
    357                     // receipt of a PUT/POST message without a Content-length header,
    358                     // even if the request has no payload.
    359                     // Since Java will not generate a Content-length header unless
    360                     // we use the output stream, we create an output stream for PUT/POST
    361                     // even if there is no payload.
    362                     if (requestBody != null) {
    363                         BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
    364                         bwr.write(requestBody);
    365                         bwr.flush();
     354                    try (OutputStream out = activeConnection.getOutputStream()) {
     355
     356                        // It seems that certain bits of the Ruby API are very unhappy upon
     357                        // receipt of a PUT/POST message without a Content-length header,
     358                        // even if the request has no payload.
     359                        // Since Java will not generate a Content-length header unless
     360                        // we use the output stream, we create an output stream for PUT/POST
     361                        // even if there is no payload.
     362                        if (requestBody != null) {
     363                            BufferedWriter bwr = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
     364                            bwr.write(requestBody);
     365                            bwr.flush();
     366                        }
    366367                    }
    367                     out.close();
    368368                }
    369369
     
    442442        }
    443443    }
    444    
     444
    445445    protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor) throws SdsTransferException {
    446446        urlStr = getBaseUrl() + urlStr;
    447         try {
     447        try {
    448448            URL url = null;
    449449            try {
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsConnection.java

    r29854 r30738  
    2121 */
    2222public class SdsConnection {
    23        
     23   
    2424    protected boolean cancel = false;
    2525    protected HttpURLConnection activeConnection;
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialAgent.java

    r30737 r30738  
    120120    }
    121121
    122         @Override
    123         public void storeOAuthAccessToken(OAuthToken accessToken)
    124                         throws CredentialsAgentException {
    125                 // no-op
    126                
    127         }
    128        
     122    @Override
     123    public void storeOAuthAccessToken(OAuthToken accessToken)
     124            throws CredentialsAgentException {
     125        // no-op
     126       
     127    }
     128   
    129129    @Override
    130130    public CredentialsAgentResponse getCredentials(RequestorType requestorType, String host, boolean noSuccessWithLastResponse) throws CredentialsAgentException{
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialDialog.java

    r28160 r30738  
    1111public class SdsCredentialDialog extends CredentialDialog {
    1212
    13         static public SdsCredentialDialog getSdsApiCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) {
     13    static public SdsCredentialDialog getSdsApiCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) {
    1414        SdsCredentialDialog dialog = new SdsCredentialDialog(saveUsernameAndPasswordCheckboxText);
    1515        dialog.prepareForSdsApiCredentials(username, password);
     
    2121
    2222    public SdsCredentialDialog(String saveUsernameAndPasswordCheckboxText) {
    23         super(saveUsernameAndPasswordCheckboxText);
     23        super(saveUsernameAndPasswordCheckboxText);
    2424    }
    25        
     25       
    2626    public void prepareForSdsApiCredentials(String username, String password) {
    2727        setTitle(tr("Enter credentials for Separate Data Store API"));
     
    3333    private static class SdsApiCredentialsPanel extends CredentialPanel {
    3434
    35                 @Override
     35        @Override
    3636        protected void build() {
    3737            super.build();
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsDiskAccessAction.java

    r30666 r30738  
    1616@SuppressWarnings("serial")
    1717public abstract class SdsDiskAccessAction extends DiskAccessAction {
    18        
     18   
    1919    public SdsDiskAccessAction(String name, String iconName, String tooltip,
    20                         Shortcut shortcut) {
    21                 super(name, iconName, tooltip, shortcut);
    22         }
     20            Shortcut shortcut) {
     21        super(name, iconName, tooltip, shortcut);
     22    }
    2323
    24         public static SwingFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title) {
     24    public static SwingFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title) {
    2525        String curDir = Main.pref.get("lastDirectory");
    2626        if (curDir.equals("")) {
     
    3535        fc.setMultiSelectionEnabled(multiple);
    3636        fc.setAcceptAllFileFilterUsed(false);
    37                        
     37               
    3838        fc.setFileFilter(new FileFilter() {
    39                 public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
    40                         public String getDescription() { return (tr("SDS data file")); }
     39            public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
     40            public String getDescription() { return (tr("SDS data file")); }
    4141        });     
    4242
     
    8383       
    8484        fc.setFileFilter(new FileFilter() {
    85                 public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
    86                         public String getDescription() { return (tr("SDS data file")); }
     85            public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); }
     86            public String getDescription() { return (tr("SDS data file")); }
    8787        });
    8888       
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsLoadAction.java

    r30737 r30738  
    2626@SuppressWarnings("serial")
    2727public class SdsLoadAction extends SdsDiskAccessAction {
    28        
    29         private SeparateDataStorePlugin plugin;
     28   
     29    private SeparateDataStorePlugin plugin;
    3030
    3131    public SdsLoadAction(SeparateDataStorePlugin p) {
    3232        super(tr("Load..."), "sds_load", tr("Load separate data store data from a file."), null);
    33         plugin = p;
     33        plugin = p;
    3434    }
    3535   
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsMenu.java

    r29854 r30738  
    5656
    5757    void setEnabledState() {
    58         boolean en = (Main.map != null) && (Main.map.mapView != null) && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer);
    59         loadItem.setEnabled(en);
    60         saveItem.setEnabled(en);
     58        boolean en = (Main.map != null) && (Main.map.mapView != null) && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer);
     59        loadItem.setEnabled(en);
     60        saveItem.setEnabled(en);
    6161    }
    6262 
    63         @Override
    64         public void activeLayerChange(Layer oldLayer, Layer newLayer) { setEnabledState(); }
     63    @Override
     64    public void activeLayerChange(Layer oldLayer, Layer newLayer) {    setEnabledState(); }
    6565
    66         @Override
    67         public void layerAdded(Layer newLayer) { setEnabledState(); }
     66    @Override
     67    public void layerAdded(Layer newLayer) { setEnabledState(); }
    6868
    69         @Override
    70         public void layerRemoved(Layer oldLayer) { setEnabledState(); }
     69    @Override
     70    public void layerRemoved(Layer oldLayer) { setEnabledState(); }
    7171
    72         private class SdsAboutAction extends JosmAction {
     72    private class SdsAboutAction extends JosmAction {
    7373
    74             public SdsAboutAction() {
    75                 super(tr("About"), "sds", tr("Information about SDS."), null, true);
    76             }
     74        public SdsAboutAction() {
     75            super(tr("About"), "sds", tr("Information about SDS."), null, true);
     76        }
    7777
    78             public void actionPerformed(ActionEvent e) {
    79                 JPanel about = new JPanel();
     78        public void actionPerformed(ActionEvent e) {
     79            JPanel about = new JPanel();
    8080
    81                 JTextArea l = new JTextArea();
    82                 l.setLineWrap(true);
    83                 l.setWrapStyleWord(true);
    84                 l.setEditable(false);
    85                 l.setText("Separate Data Store\n\nThis plugin provides access to a \"Separate Data Store\" server. " +
    86                                 "Whenever data is loaded from the OSM API, it queries the SDS for additional tags that have been stored for the objects just loaded, " +
    87                                 "and adds these tags. When you upload data to JOSM, SDS tags will again be separated and, instead of sending them to OSM, they will be uplaoded to SDS." +
    88                                 "\n\n" +
    89                                 "This depends on SDS tags starting with a special prefix, which can be configured in the SDS preferences." +
    90                                 "\n\n" +
    91                                 "Using the SDS server will usually require an account to be set up there, which is completely independent of your OSM account.");
    92                
    93                 l.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    94                 l.setOpaque(false);
    95                 l.setPreferredSize(new Dimension(500,300));
    96                 JScrollPane sp = new JScrollPane(l);
    97                 sp.setBorder(null);
    98                 sp.setOpaque(false);
    99                                
    100                 about.add(sp);
    101                
    102                 about.setPreferredSize(new Dimension(500,300));
     81            JTextArea l = new JTextArea();
     82            l.setLineWrap(true);
     83            l.setWrapStyleWord(true);
     84            l.setEditable(false);
     85            l.setText("Separate Data Store\n\nThis plugin provides access to a \"Separate Data Store\" server. " +
     86                    "Whenever data is loaded from the OSM API, it queries the SDS for additional tags that have been stored for the objects just loaded, " +
     87                    "and adds these tags. When you upload data to JOSM, SDS tags will again be separated and, instead of sending them to OSM, they will be uplaoded to SDS." +
     88                    "\n\n" +
     89                    "This depends on SDS tags starting with a special prefix, which can be configured in the SDS preferences." +
     90                    "\n\n" +
     91                    "Using the SDS server will usually require an account to be set up there, which is completely independent of your OSM account.");
     92           
     93            l.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
     94            l.setOpaque(false);
     95            l.setPreferredSize(new Dimension(500,300));
     96            JScrollPane sp = new JScrollPane(l);
     97            sp.setBorder(null);
     98            sp.setOpaque(false);
     99                       
     100            about.add(sp);
     101           
     102            about.setPreferredSize(new Dimension(500,300));
    103103
    104                 JOptionPane.showMessageDialog(Main.parent, about, tr("About SDS..."),
    105                         JOptionPane.INFORMATION_MESSAGE, null);
    106             }
    107         }
    108        
    109         private class SdsPreferencesAction extends JosmAction implements Runnable {
     104            JOptionPane.showMessageDialog(Main.parent, about, tr("About SDS..."),
     105                    JOptionPane.INFORMATION_MESSAGE, null);
     106        }
     107    }
     108   
     109    private class SdsPreferencesAction extends JosmAction implements Runnable {
    110110
    111             private SdsPreferencesAction() {
    112                 super(tr("Preferences..."), "preference", tr("Open a preferences dialog for SDS."),
    113                         null, true);
    114                 putValue("help", ht("/Action/Preferences"));
    115             }
     111        private SdsPreferencesAction() {
     112            super(tr("Preferences..."), "preference", tr("Open a preferences dialog for SDS."),
     113                    null, true);
     114            putValue("help", ht("/Action/Preferences"));
     115        }
    116116
    117             /**
    118              * Launch the preferences dialog.
    119              */
    120             public void actionPerformed(ActionEvent e) {
    121                 run();
    122             }
     117        /**
     118         * Launch the preferences dialog.
     119         */
     120        public void actionPerformed(ActionEvent e) {
     121            run();
     122        }
    123123
    124             public void run() {
    125                 PreferenceDialog pd = new PreferenceDialog(Main.parent);
    126                 // unusual reflection mechanism to cater for older JOSM versions where
    127                 // the selectPreferencesTabByName method was not public
    128                 try {
    129                         Method sptbn = pd.getClass().getMethod("selectPreferencesTabByName", String.class);
    130                         sptbn.invoke(pd, "sds");
    131                 } catch (Exception ex) {
    132                         // ignore
    133                 }
    134                 pd.setVisible(true);
    135             }
    136         }
     124        public void run() {
     125            PreferenceDialog pd = new PreferenceDialog(Main.parent);
     126            // unusual reflection mechanism to cater for older JOSM versions where
     127            // the selectPreferencesTabByName method was not public
     128            try {
     129                Method sptbn = pd.getClass().getMethod("selectPreferencesTabByName", String.class);
     130                sptbn.invoke(pd, "sds");
     131            } catch (Exception ex) {
     132                // ignore
     133            }
     134            pd.setVisible(true);
     135        }
     136    }
    137137
    138138
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriter.java

    r30737 r30738  
    2727public class SdsOsmWriter extends OsmWriter {
    2828
    29         private SeparateDataStorePlugin plugin;
    30        
     29    private SeparateDataStorePlugin plugin;
     30   
    3131    public SdsOsmWriter(SeparateDataStorePlugin plugin, PrintWriter out, boolean osmConform, String version) {
    3232        super(out, osmConform, version);
     
    4343            Collections.sort(entries, byKeyComparator);
    4444            for (Entry<String, String> e : entries) {
    45                 String key = e.getKey();
     45                String key = e.getKey();
    4646                if (!(osm instanceof Changeset) && ("created_by".equals(key))) continue;
    4747                if (key.startsWith(plugin.getIgnorePrefix())) continue;         
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriterFactory.java

    r28160 r30738  
    1515public class SdsOsmWriterFactory extends OsmWriterFactory {
    1616
    17         SeparateDataStorePlugin plugin;
    18        
    19         public SdsOsmWriterFactory(SeparateDataStorePlugin plugin) {
    20                 this.plugin = plugin;
    21         }
    22        
    23         @Override
     17    SeparateDataStorePlugin plugin;
     18   
     19    public SdsOsmWriterFactory(SeparateDataStorePlugin plugin) {
     20        this.plugin = plugin;
     21    }
     22   
     23    @Override
    2424    protected OsmWriter createOsmWriterImpl(PrintWriter out, boolean osmConform, String version) {
    2525        return new SdsOsmWriter(plugin, out, osmConform, version);
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsParser.java

    r28160 r30738  
    5454        {
    5555            String type = atts.getValue("osm_type");
    56             String id = atts.getValue("osm_id");        
     56            String id = atts.getValue("osm_id");        
    5757            currentPrimitive = dataSet.getPrimitiveById(Long.parseLong(id), OsmPrimitiveType.fromApiTypeName(type));
    5858            if (currentPrimitive == null && ensureMatch) {
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsPluginPreferences.java

    r28160 r30738  
    3535   
    3636    public SdsPluginPreferences() {
    37         super("sds", tr("Separate Data Store"), tr("Configures access to the Separate Data Store."));
     37        super("sds", tr("Separate Data Store"), tr("Configures access to the Separate Data Store."));
    3838    }
    3939    @Override
    4040    public void addGui(final PreferenceTabbedPane gui) {
    4141        final JPanel tab = gui.createPreferenceTab(this);
    42                
     42           
    4343        final JPanel access = new JPanel(new GridBagLayout());
    4444        access.setBorder(BorderFactory.createTitledBorder(tr("Server")));
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsSaveAction.java

    r29854 r30738  
    66import java.awt.event.ActionEvent;
    77import java.io.File;
    8 import java.io.FileInputStream;
    9 import java.io.FileNotFoundException;
    108import java.io.FileOutputStream;
    119import java.io.IOException;
     
    2119import org.openstreetmap.josm.gui.layer.Layer;
    2220import org.openstreetmap.josm.gui.layer.OsmDataLayer;
     21import org.openstreetmap.josm.tools.Utils;
    2322
    24 @SuppressWarnings("serial")
    2523public class SdsSaveAction extends SdsDiskAccessAction {
    2624
     
    3028    }
    3129
     30    @Override
    3231    public void actionPerformed(ActionEvent e) {
    3332        if (!isEnabled())
     
    4039        if (Main.isDisplayingMapView() && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer))
    4140            layer = Main.map.mapView.getActiveLayer();
    42        
     41
    4342        if (layer == null)
    4443            return false;
     
    6463            if (file.exists()) {
    6564                tmpFile = new File(file.getPath() + "~");
    66                 copy(file, tmpFile);
     65                Utils.copyFile(file, tmpFile);
    6766            }
    6867
     
    7069            Writer writer = new OutputStreamWriter(out, "UTF-8");
    7170
    72             SdsWriter w = new SdsWriter(new PrintWriter(writer));
    7371            layer.data.getReadLock().lock();
    74             try {
     72            try (SdsWriter w = new SdsWriter(new PrintWriter(writer))) {
    7573                w.header();
    7674                for (IPrimitive p : layer.data.allNonDeletedPrimitives()) {
     
    7876                }
    7977                w.footer();
    80                 w.close();
    8178            } finally {
    8279                layer.data.getReadLock().unlock();
     
    8784            }
    8885        } catch (IOException e) {
    89             e.printStackTrace();
     86            Main.error(e);
    9087            JOptionPane.showMessageDialog(
    9188                    Main.parent,
     
    9996                // be deleted.  So, restore the backup if we made one.
    10097                if (tmpFile != null && tmpFile.exists()) {
    101                     copy(tmpFile, file);
     98                    Utils.copyFile(tmpFile, file);
    10299                }
    103100            } catch (IOException e2) {
    104                 e2.printStackTrace();
     101                Main.error(e2);
    105102                JOptionPane.showMessageDialog(
    106103                        Main.parent,
     
    113110        return true;
    114111    }
    115 
    116     private void copy(File src, File dst) throws IOException {
    117         FileInputStream srcStream;
    118         FileOutputStream dstStream;
    119         try {
    120             srcStream = new FileInputStream(src);
    121             dstStream = new FileOutputStream(dst);
    122         } catch (FileNotFoundException e) {
    123             JOptionPane.showMessageDialog(Main.parent, tr("Could not back up file. Exception is: {0}", e
    124                     .getMessage()), tr("Error"), JOptionPane.ERROR_MESSAGE);
    125             return;
    126         }
    127         byte buf[] = new byte[1 << 16];
    128         int len;
    129         while ((len = srcStream.read(buf)) != -1) {
    130             dstStream.write(buf, 0, len);
    131         }
    132         srcStream.close();
    133         dstStream.close();
    134     }
    135112}
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsWriter.java

    r28160 r30738  
    2929
    3030    public void write(IPrimitive what, Map<String,String> tags) {
    31         out.print("<osm_shadow osm_type=\"");
    32         out.print(what.getType().getAPIName());
    33         out.print("\" osm_id=\"");
    34         out.print(what.getId());
    35         out.println("\">");
     31        out.print("<osm_shadow osm_type=\"");
     32        out.print(what.getType().getAPIName());
     33        out.print("\" osm_id=\"");
     34        out.print(what.getId());
     35        out.println("\">");
    3636       
    37         if (tags != null) {
    38                 for(Entry<String,String> e : tags.entrySet()) {
    39                         out.println("    <tag k='"+ XmlWriter.encode(e.getKey()) +
    40                                         "' v='"+XmlWriter.encode(e.getValue())+ "' />");
    41                 }
    42         }
    43        
    44         out.println("</osm_shadow>");
     37        if (tags != null) {
     38            for(Entry<String,String> e : tags.entrySet()) {
     39                out.println("    <tag k='"+ XmlWriter.encode(e.getKey()) +
     40                        "' v='"+XmlWriter.encode(e.getValue())+ "' />");
     41            }
     42        }
     43       
     44        out.println("</osm_shadow>");
    4545    }
    4646
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SeparateDataStorePlugin.java

    r30737 r30738  
    2929{
    3030
    31         public HashMap<Long, IPrimitive> originalNodes = new HashMap<>();
    32         public HashMap<Long, IPrimitive> originalWays = new HashMap<>();
    33         public HashMap<Long, IPrimitive> originalRelations = new HashMap<>();
    34        
    35         public ArrayList<QueueItem> uploadQueue = new ArrayList<>();
    36        
    37         private PrimitiveVisitor learnVisitor = new PrimitiveVisitor() {
    38                 public void visit(INode i) { originalNodes.put(i.getId(), i); }
    39                 public void visit(IWay i) { originalWays.put(i.getId(), i); }
    40                 public void visit(IRelation i) { originalRelations.put(i.getId(), i); }
    41         };
    42        
    43         class QueueItem {
    44                 public IPrimitive primitive;
    45                 public HashMap<String,String> tags;
    46                 public boolean sdsOnly;
    47                 public boolean processed;
    48                 public QueueItem(IPrimitive p, HashMap<String,String> t, boolean s) {
    49                         primitive = p;
    50                         tags = t;
    51                         sdsOnly = s;
    52                         processed = false;
    53                 }
    54         }
    55        
     31    public HashMap<Long, IPrimitive> originalNodes = new HashMap<>();
     32    public HashMap<Long, IPrimitive> originalWays = new HashMap<>();
     33    public HashMap<Long, IPrimitive> originalRelations = new HashMap<>();
     34   
     35    public ArrayList<QueueItem> uploadQueue = new ArrayList<>();
     36   
     37    private PrimitiveVisitor learnVisitor = new PrimitiveVisitor() {
     38        public void visit(INode i) { originalNodes.put(i.getId(), i); }
     39        public void visit(IWay i) { originalWays.put(i.getId(), i); }
     40        public void visit(IRelation i) { originalRelations.put(i.getId(), i); }
     41    };
     42   
     43    class QueueItem {
     44        public IPrimitive primitive;
     45        public HashMap<String,String> tags;
     46        public boolean sdsOnly;
     47        public boolean processed;
     48        public QueueItem(IPrimitive p, HashMap<String,String> t, boolean s) {
     49            primitive = p;
     50            tags = t;
     51            sdsOnly = s;
     52            processed = false;
     53        }
     54    }
     55   
    5656    /**
    5757     * Creates the plugin
     
    6060    {
    6161        super(info);
    62         System.out.println("initializing SDS plugin");
    63        
    64         // this lets us see what JOSM load from the server, and augment it with our data:
     62        System.out.println("initializing SDS plugin");
     63       
     64        // this lets us see what JOSM load from the server, and augment it with our data:
    6565        OsmReader.registerPostprocessor(new ReadPostprocessor(this));
    6666       
     
    7979    }
    8080
    81         public String getIgnorePrefix() {
     81    public String getIgnorePrefix() {
    8282        return Main.pref.get("sds-server.tag-prefix", "hot:");
    83         }
    84        
    85         public IPrimitive getOriginalPrimitive(IPrimitive other) {
    86                 switch (other.getType()) {
    87                 case NODE: return originalNodes.get(other.getId());
    88                 case WAY: return originalWays.get(other.getId());
    89                 case RELATION: return originalRelations.get(other.getId());
    90                 }
    91                 return null;   
    92         }
    93        
    94         protected void enqueueForUpload(IPrimitive prim, HashMap<String, String> tags, boolean onlySds) {
    95                 uploadQueue.add(new QueueItem(prim, tags, onlySds));
    96         }
    97        
    98         /**
    99         * Stores the given primitive in the plugin's cache in order to
    100         * determine changes later.
    101         * @param prim
    102         */
    103         protected void learn(IPrimitive prim) {
    104                 if (prim instanceof OsmPrimitive) {
    105                         ((OsmPrimitive)prim).save().accept(learnVisitor);
    106                 } else {
    107                         prim.accept(learnVisitor);
    108                 }
    109         }
    110        
    111         /**
    112         * removes all elements from the upload queue that have the processed flag set.
    113         */
    114         protected void clearQueue() {
    115                 ArrayList<QueueItem> newQueue = new ArrayList<>();
    116                 for (QueueItem q : uploadQueue) {
    117                         if (!q.processed) newQueue.add(q);
    118                 }
    119                 uploadQueue = newQueue;
    120         }
    121        
    122         /**
    123         * reset the processed flag for all elements of the queue.
    124         */
    125         protected void resetQueue() {
    126                 for (QueueItem q : uploadQueue) {
    127                         q.processed = false;
    128                 }
    129         }
     83    }
     84   
     85    public IPrimitive getOriginalPrimitive(IPrimitive other) {
     86        switch (other.getType()) {
     87        case NODE: return originalNodes.get(other.getId());
     88        case WAY: return originalWays.get(other.getId());
     89        case RELATION: return originalRelations.get(other.getId());
     90        }
     91        return null;   
     92    }
     93   
     94    protected void enqueueForUpload(IPrimitive prim, HashMap<String, String> tags, boolean onlySds) {
     95        uploadQueue.add(new QueueItem(prim, tags, onlySds));
     96    }
     97   
     98    /**
     99    * Stores the given primitive in the plugin's cache in order to
     100    * determine changes later.
     101    * @param prim
     102    */
     103    protected void learn(IPrimitive prim) {
     104        if (prim instanceof OsmPrimitive) {
     105            ((OsmPrimitive)prim).save().accept(learnVisitor);
     106        } else {
     107            prim.accept(learnVisitor);
     108        }
     109    }
     110   
     111    /**
     112    * removes all elements from the upload queue that have the processed flag set.
     113    */
     114    protected void clearQueue() {
     115        ArrayList<QueueItem> newQueue = new ArrayList<>();
     116        for (QueueItem q : uploadQueue) {
     117            if (!q.processed) newQueue.add(q);
     118        }
     119        uploadQueue = newQueue;
     120    }
     121   
     122    /**
     123    * reset the processed flag for all elements of the queue.
     124    */
     125    protected void resetQueue() {
     126        for (QueueItem q : uploadQueue) {
     127            q.processed = false;
     128        }
     129    }
    130130
    131131    public PreferenceSetting getPreferenceSetting() {
  • applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/WritePostprocessor.java

    r29854 r30738  
    1313public class WritePostprocessor implements OsmServerWritePostprocessor {
    1414
    15         SeparateDataStorePlugin plugin;
     15    SeparateDataStorePlugin plugin;
    1616
    17         public WritePostprocessor(SeparateDataStorePlugin plugin) {
    18                 this.plugin = plugin;
    19         }       
     17    public WritePostprocessor(SeparateDataStorePlugin plugin) {
     18        this.plugin = plugin;
     19    }
    2020
    21         @Override
    22         public void postprocessUploadedPrimitives(Collection<IPrimitive> primitives,
    23                         ProgressMonitor progress) {
    24                
    25             StringWriter swriter = new StringWriter();
    26             SdsWriter sdsWriter = new SdsWriter(new PrintWriter(swriter));
    27             sdsWriter.header();
    28             boolean somethingWritten = false;
    29            
    30             for (IPrimitive p : primitives) {
    31                         for (QueueItem q : plugin.uploadQueue) {
    32                                 if (q.primitive.equals(p) && !q.sdsOnly) {
    33                                         sdsWriter.write(q.primitive, q.tags);
    34                                         somethingWritten = true;
    35                                         q.processed = true;
    36                                         continue;
    37                                 }
    38                         }
    39             }
    40            
    41                 for (QueueItem q : plugin.uploadQueue) {
    42                         if (q.sdsOnly) {
    43                                 sdsWriter.write(q.primitive, q.tags);
    44                                 somethingWritten = true;
    45                                 q.processed = true;
    46                         }
    47                 }
     21    @Override
     22    public void postprocessUploadedPrimitives(Collection<IPrimitive> primitives, ProgressMonitor progress) {
    4823
    49                 if (somethingWritten) {
    50                         sdsWriter.footer();
     24        StringWriter swriter = new StringWriter();
     25        try (SdsWriter sdsWriter = new SdsWriter(new PrintWriter(swriter))) {
     26            sdsWriter.header();
     27            boolean somethingWritten = false;
    5128
    52                         SdsApi api = SdsApi.getSdsApi();
    53                         System.out.println("sending message:\n" + swriter.toString());
    54                         api.updateSds(swriter.toString(), progress);
    55                 }
    56                
    57                 sdsWriter.close();
    58                
    59                 for (IPrimitive p : primitives) {
    60                         plugin.learn(p);
    61                 }
     29            for (IPrimitive p : primitives) {
     30                for (QueueItem q : plugin.uploadQueue) {
     31                    if (q.primitive.equals(p) && !q.sdsOnly) {
     32                        sdsWriter.write(q.primitive, q.tags);
     33                        somethingWritten = true;
     34                        q.processed = true;
     35                        continue;
     36                    }
     37                }
     38            }
    6239
    63                 for (QueueItem q : plugin.uploadQueue) {
    64                         if (q.sdsOnly) {
    65                                 q.primitive.setModified(false);
    66                                 plugin.learn(q.primitive);
    67                         }
    68                 }
    69                
    70                 plugin.clearQueue();
    71                 // TODO: if exception -> resetQueue
    72         }
     40            for (QueueItem q : plugin.uploadQueue) {
     41                if (q.sdsOnly) {
     42                    sdsWriter.write(q.primitive, q.tags);
     43                    somethingWritten = true;
     44                    q.processed = true;
     45                }
     46            }
     47
     48            if (somethingWritten) {
     49                sdsWriter.footer();
     50
     51                SdsApi api = SdsApi.getSdsApi();
     52                System.out.println("sending message:\n" + swriter.toString());
     53                api.updateSds(swriter.toString(), progress);
     54            }
     55        }
     56
     57        for (IPrimitive p : primitives) {
     58            plugin.learn(p);
     59        }
     60
     61        for (QueueItem q : plugin.uploadQueue) {
     62            if (q.sdsOnly) {
     63                q.primitive.setModified(false);
     64                plugin.learn(q.primitive);
     65            }
     66        }
     67
     68        plugin.clearQueue();
     69        // TODO: if exception -> resetQueue
     70    }
    7371
    7472}
  • applications/editors/josm/plugins/smed/src/panels/PanelChan.java

    r29894 r30738  
    2828                        panelStbd.setVisible(false);
    2929                        panelSaw.setVisible(false);
    30                         dlg.panelMain.moreButton.setVisible(false);
    31                         dlg.panelMain.saveButton.setEnabled(false);
     30                        SmedAction.panelMain.moreButton.setVisible(false);
     31                        SmedAction.panelMain.saveButton.setEnabled(false);
    3232                        topmarkButton.setVisible(false);
    3333                        lightButton.setVisible(false);
    34                         Shp shp = dlg.panelMain.mark.getShape();
     34                        Shp shp = SmedAction.panelMain.mark.getShape();
    3535                        if (portButton.isSelected()) {
    36                                 dlg.panelMain.mark.setCategory(Cat.LAM_PORT);
     36                                SmedAction.panelMain.mark.setCategory(Cat.LAM_PORT);
    3737                                if (panelPort.shapes.containsKey(shp)) {
    3838                                        panelPort.shapes.get(shp).setSelected(true);
    3939                                } else {
    4040                                        panelPort.shapeButtons.clearSelection();
    41                                         dlg.panelMain.mark.setShape(Shp.UNKSHP);
     41                                        SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    4242                                }
    4343                                panelPort.alShape.actionPerformed(null);
     
    4848                        }
    4949                        if (stbdButton.isSelected()) {
    50                                 dlg.panelMain.mark.setCategory(Cat.LAM_STBD);
     50                                SmedAction.panelMain.mark.setCategory(Cat.LAM_STBD);
    5151                                if (panelStbd.shapes.containsKey(shp)) {
    5252                                        panelStbd.shapes.get(shp).setSelected(true);
    5353                                } else {
    5454                                        panelStbd.shapeButtons.clearSelection();
    55                                         dlg.panelMain.mark.setShape(Shp.UNKSHP);
     55                                        SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    5656                                }
    5757                                panelStbd.alShape.actionPerformed(null);
     
    6262                        }
    6363                        if (prefStbdButton.isSelected()) {
    64                                 dlg.panelMain.mark.setCategory(Cat.LAM_PSTBD);
     64                                SmedAction.panelMain.mark.setCategory(Cat.LAM_PSTBD);
    6565                                if (panelPort.shapes.containsKey(shp)) {
    6666                                        panelPort.shapes.get(shp).setSelected(true);
    6767                                } else {
    6868                                        panelPort.shapeButtons.clearSelection();
    69                                         dlg.panelMain.mark.setShape(Shp.UNKSHP);
     69                                        SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    7070                                }
    7171                                panelPort.alShape.actionPerformed(null);
     
    7676                        }
    7777                        if (prefPortButton.isSelected()) {
    78                                 dlg.panelMain.mark.setCategory(Cat.LAM_PPORT);
     78                                SmedAction.panelMain.mark.setCategory(Cat.LAM_PPORT);
    7979                                if (panelStbd.shapes.containsKey(shp)) {
    8080                                        panelStbd.shapes.get(shp).setSelected(true);
    8181                                } else {
    8282                                        panelStbd.shapeButtons.clearSelection();
    83                                         dlg.panelMain.mark.setShape(Shp.UNKSHP);
     83                                        SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    8484                                }
    8585                                panelStbd.alShape.actionPerformed(null);
     
    9090                        }
    9191                        if (safeWaterButton.isSelected()) {
    92                                 dlg.panelMain.mark.setCategory(Cat.NOCAT);
     92                                SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
    9393                                panelSaw.setVisible(true);
    9494                                if (panelSaw.shapes.containsKey(shp)) {
     
    9696                                } else {
    9797                                        panelSaw.shapeButtons.clearSelection();
    98                                         dlg.panelMain.mark.setShape(Shp.UNKSHP);
     98                                        SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    9999                                }
    100100                                panelSaw.alShape.actionPerformed(null);
     
    104104                                safeWaterButton.setBorderPainted(false);
    105105                        }
    106                         topmarkButton.setVisible(dlg.panelMain.mark.testValid());
    107                         lightButton.setVisible(dlg.panelMain.mark.testValid());
    108                         dlg.panelMain.panelMore.syncPanel();
     106                        topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
     107                        lightButton.setVisible(SmedAction.panelMain.mark.testValid());
     108                        SmedAction.panelMain.panelMore.syncPanel();
    109109                }
    110110        };
     
    113113                public void actionPerformed(java.awt.event.ActionEvent e) {
    114114                        if (topmarkButton.isSelected()) {
    115                                 if (SeaMark.GrpMAP.get(dlg.panelMain.mark.getObject()) == Grp.SAW) {
    116                                         dlg.panelMain.mark.setTopmark(Top.SPHERE);
    117                                         dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
    118                                         dlg.panelMain.mark.setTopColour(Col.RED);
     115                                if (SeaMark.GrpMAP.get(SmedAction.panelMain.mark.getObject()) == Grp.SAW) {
     116                                        SmedAction.panelMain.mark.setTopmark(Top.SPHERE);
     117                                        SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
     118                                        SmedAction.panelMain.mark.setTopColour(Col.RED);
    119119                                } else {
    120120                                        switch (dlg.panelMain.mark.getCategory()) {
  • applications/editors/josm/plugins/smed/src/panels/PanelChr.java

    r30737 r30738  
    6767                        }
    6868                        String str = charBox.getText();
    69                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, str);
     69                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, str);
    7070                        if (!str.contains("Al")) {
    71                                 col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
    72                                 dlg.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
     71                                col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
     72                                SmedAction.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
    7373                        } else {
    74                                 col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, 0)));
     74                                col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0)));
    7575                        }
    7676                }
     
    8080                        public void focusLost(java.awt.event.FocusEvent e) {
    8181                        String str = charBox.getText();
    82                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, str);
     82                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, str);
    8383                        EnumSet<Chr> set = EnumSet.noneOf(Chr.class);
    8484                        for (EnumSet<Chr> map : SeaMark.ChrMAP.keySet()) {
     
    9999                        }
    100100                        if (!str.contains("Al")) {
    101                                 col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
    102                                 dlg.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
     101                                col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
     102                                SmedAction.panelMain.mark.setLightAtt(Att.ALT, 0, Col.UNKCOL);
    103103                        } else {
    104                                 col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, 0)));
     104                                col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0)));
    105105                        }
    106106                }
     
    141141
    142142        public void syncPanel() {
    143                 String str = (String)dlg.panelMain.mark.getLightAtt(Att.CHR, 0);
     143                String str = (String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, 0);
    144144                charBox.setText(str);
    145145                EnumSet<Chr> set = EnumSet.noneOf(Chr.class);
     
    151151                }
    152152                if (!str.contains("Al")) {
    153                         col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
     153                        col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
    154154                } else {
    155                         col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, 0)));
     155                        col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0)));
    156156                }
    157                 col1Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, 0)));
     157                col1Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, 0)));
    158158                for (Chr chr : buttons.keySet()) {
    159159                        JToggleButton button = buttons.get(chr);
  • applications/editors/josm/plugins/smed/src/panels/PanelCol.java

    r30737 r30738  
    4141                                if (button.isSelected()) {
    4242                                        if (ent == Ent.LIGHT) {
    43                                                 if (((String) dlg.panelMain.mark.getLightAtt(Att.CHR, 0)).contains("Al")) {
    44                                                         if (((button == delButton) && (dlg.panelMain.mark.getLightAtt(Att.ALT, 0) == Col.UNKCOL))
    45                                                                         || (dlg.panelMain.mark.getLightAtt(Att.COL, 0) == Col.UNKCOL)) {
    46                                                                 dlg.panelMain.mark.setLightAtt(Att.COL, 0, col);
    47                                                                 dlg.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
     43                                                if (((String) SmedAction.panelMain.mark.getLightAtt(Att.CHR, 0)).contains("Al")) {
     44                                                        if (((button == delButton) && (SmedAction.panelMain.mark.getLightAtt(Att.ALT, 0) == Col.UNKCOL))
     45                                                                        || (SmedAction.panelMain.mark.getLightAtt(Att.COL, 0) == Col.UNKCOL)) {
     46                                                                SmedAction.panelMain.mark.setLightAtt(Att.COL, 0, col);
     47                                                                SmedAction.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
    4848                                                        } else {
    49                                                                 dlg.panelMain.mark.setLightAtt(Att.ALT, 0, col);
    50                                                                 dlg.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
     49                                                                SmedAction.panelMain.mark.setLightAtt(Att.ALT, 0, col);
     50                                                                SmedAction.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
    5151                                                        }
    5252                                                } else {
    53                                                         dlg.panelMain.mark.setLightAtt(Att.COL, 0, col);
    54                                                         dlg.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
    55                                                         dlg.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
     53                                                        SmedAction.panelMain.mark.setLightAtt(Att.COL, 0, col);
     54                                                        SmedAction.panelMain.panelLit.panelChr.col1Label.setBackground(SeaMark.ColMAP.get(col));
     55                                                        SmedAction.panelMain.panelLit.panelChr.col2Label.setBackground(SeaMark.ColMAP.get(col));
    5656                                                }
    5757                                                button.setBorderPainted(true);
    5858                                        } else {
    5959                                                if (button == delButton) {
    60                                                         dlg.panelMain.mark.subColour(ent, stackIdx);
     60                                                        SmedAction.panelMain.mark.subColour(ent, stackIdx);
    6161                                                } else if (button == addButton) {
    6262                                                        if (stackCol.size() != 0)
    6363                                                                stackIdx++;
    6464                                                        if (stackCol.size() == 0)
    65                                                                 dlg.panelMain.mark.setColour(ent, col);
     65                                                                SmedAction.panelMain.mark.setColour(ent, col);
    6666                                                        else
    67                                                                 switch (dlg.panelMain.mark.getPattern(ent)) {
     67                                                                switch (SmedAction.panelMain.mark.getPattern(ent)) {
    6868                                                                case NOPAT:
    6969                                                                        break;
     
    7171                                                                case CROSS:
    7272                                                                        if (stackCol.size() < 2)
    73                                                                                 dlg.panelMain.mark.addColour(ent, stackIdx, col);
     73                                                                                SmedAction.panelMain.mark.addColour(ent, stackIdx, col);
    7474                                                                        break;
    7575                                                                case SQUARED:
    7676                                                                        if (stackCol.size() < 4)
    77                                                                                 dlg.panelMain.mark.addColour(ent, stackIdx, col);
     77                                                                                SmedAction.panelMain.mark.addColour(ent, stackIdx, col);
    7878                                                                        break;
    7979                                                                default:
    80                                                                         dlg.panelMain.mark.addColour(ent, stackIdx, col);
     80                                                                        SmedAction.panelMain.mark.addColour(ent, stackIdx, col);
    8181                                                                        break;
    8282                                                                }
    8383                                                } else {
    84                                                         dlg.panelMain.mark.setColour(ent, stackIdx, col);
     84                                                        SmedAction.panelMain.mark.setColour(ent, stackIdx, col);
    8585                                                }
    8686                                                syncPanel();
     
    150150                        for (Col col : colours.keySet()) {
    151151                                JRadioButton button = colours.get(col);
    152                                 if (dlg.panelMain.mark.getLightAtt(Att.COL, 0) == col) {
     152                                if (SmedAction.panelMain.mark.getLightAtt(Att.COL, 0) == col) {
    153153                                        button.setBorderPainted(true);
    154154                                } else
     
    157157                } else {
    158158                        int idx;
    159                         for (idx = 0; dlg.panelMain.mark.getColour(ent, idx) != Col.UNKCOL; idx++) {
     159                        for (idx = 0; SmedAction.panelMain.mark.getColour(ent, idx) != Col.UNKCOL; idx++) {
    160160                                if (stackCol.size() <= idx) {
    161161                                        stackCol.add(idx, new JRadioButton(new ImageIcon(getClass().getResource("/images/ColourButton.png"))));
     
    185185                                        JRadioButton btnI = stackCol.get(idx);
    186186                                        btnI.setBounds(2, (2 + (idx * height)), 30, height);
    187                                         btnI.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getColour(ent, idx)));
     187                                        btnI.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getColour(ent, idx)));
    188188                                        if (stackIdx == idx) {
    189189                                                btnI.setBorderPainted(true);
  • applications/editors/josm/plugins/smed/src/panels/PanelFog.java

    r30737 r30738  
    3030                                JRadioButton button = fogs.get(fog);
    3131                                if (button.isSelected()) {
    32                                         dlg.panelMain.mark.setFogSound(fog);
     32                                        SmedAction.panelMain.mark.setFogSound(fog);
    3333                                        button.setBorderPainted(true);
    3434                                } else
     
    4141        private FocusListener flGroup = new FocusAdapter() {
    4242                public void focusLost(java.awt.event.FocusEvent e) {
    43                         dlg.panelMain.mark.setFogGroup(groupBox.getText());
     43                        SmedAction.panelMain.mark.setFogGroup(groupBox.getText());
    4444                }
    4545        };
     
    4848        private FocusListener flPeriod = new FocusAdapter() {
    4949                public void focusLost(java.awt.event.FocusEvent e) {
    50                         dlg.panelMain.mark.setFogPeriod(periodBox.getText());
     50                        SmedAction.panelMain.mark.setFogPeriod(periodBox.getText());
    5151                }
    5252        };
     
    5555        private FocusListener flSeq = new FocusAdapter() {
    5656                public void focusLost(java.awt.event.FocusEvent e) {
    57                         dlg.panelMain.mark.setFogSequence(seqBox.getText());
     57                        SmedAction.panelMain.mark.setFogSequence(seqBox.getText());
    5858                }
    5959        };
     
    6262        private FocusListener flRange = new FocusAdapter() {
    6363                public void focusLost(java.awt.event.FocusEvent e) {
    64                         dlg.panelMain.mark.setFogRange(rangeBox.getText());
     64                        SmedAction.panelMain.mark.setFogRange(rangeBox.getText());
    6565                }
    6666        };
     
    120120                for (Fog fog : fogs.keySet()) {
    121121                        JRadioButton button = fogs.get(fog);
    122                         button.setBorderPainted(dlg.panelMain.mark.getFogSound() == fog);
     122                        button.setBorderPainted(SmedAction.panelMain.mark.getFogSound() == fog);
    123123                }
    124                 groupBox.setText(dlg.panelMain.mark.getFogGroup());
    125                 seqBox.setText(dlg.panelMain.mark.getFogSequence());
    126                 periodBox.setText(dlg.panelMain.mark.getFogPeriod());
    127                 rangeBox.setText(dlg.panelMain.mark.getFogRange());
     124                groupBox.setText(SmedAction.panelMain.mark.getFogGroup());
     125                seqBox.setText(SmedAction.panelMain.mark.getFogSequence());
     126                periodBox.setText(SmedAction.panelMain.mark.getFogPeriod());
     127                rangeBox.setText(SmedAction.panelMain.mark.getFogRange());
    128128        }
    129129
  • applications/editors/josm/plugins/smed/src/panels/PanelHaz.java

    r30737 r30738  
    2424        private ActionListener alCat = new ActionListener() {
    2525                public void actionPerformed(java.awt.event.ActionEvent e) {
    26                         dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
     26                        SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
    2727                        if (northButton.isSelected()) {
    28                                 dlg.panelMain.mark.setCategory(Cat.CAM_NORTH);
    29                                 dlg.panelMain.mark.setObjColour(Col.BLACK);
    30                                 dlg.panelMain.mark.addObjColour(Col.YELLOW);
     28                                SmedAction.panelMain.mark.setCategory(Cat.CAM_NORTH);
     29                                SmedAction.panelMain.mark.setObjColour(Col.BLACK);
     30                                SmedAction.panelMain.mark.addObjColour(Col.YELLOW);
    3131                                northButton.setBorderPainted(true);
    3232                        } else {
     
    3434                        }
    3535                        if (southButton.isSelected()) {
    36                                 dlg.panelMain.mark.setCategory(Cat.CAM_SOUTH);
    37                                 dlg.panelMain.mark.setObjColour(Col.YELLOW);
    38                                 dlg.panelMain.mark.addObjColour(Col.BLACK);
     36                                SmedAction.panelMain.mark.setCategory(Cat.CAM_SOUTH);
     37                                SmedAction.panelMain.mark.setObjColour(Col.YELLOW);
     38                                SmedAction.panelMain.mark.addObjColour(Col.BLACK);
    3939                                southButton.setBorderPainted(true);
    4040                        } else {
     
    4242                        }
    4343                        if (eastButton.isSelected()) {
    44                                 dlg.panelMain.mark.setCategory(Cat.CAM_EAST);
    45                                 dlg.panelMain.mark.setObjColour(Col.BLACK);
    46                                 dlg.panelMain.mark.addObjColour(Col.YELLOW);
    47                                 dlg.panelMain.mark.addObjColour(Col.BLACK);
     44                                SmedAction.panelMain.mark.setCategory(Cat.CAM_EAST);
     45                                SmedAction.panelMain.mark.setObjColour(Col.BLACK);
     46                                SmedAction.panelMain.mark.addObjColour(Col.YELLOW);
     47                                SmedAction.panelMain.mark.addObjColour(Col.BLACK);
    4848                                eastButton.setBorderPainted(true);
    4949                        } else {
     
    5151                        }
    5252                        if (westButton.isSelected()) {
    53                                 dlg.panelMain.mark.setCategory(Cat.CAM_WEST);
    54                                 dlg.panelMain.mark.setObjColour(Col.YELLOW);
    55                                 dlg.panelMain.mark.addObjColour(Col.BLACK);
    56                                 dlg.panelMain.mark.addObjColour(Col.YELLOW);
     53                                SmedAction.panelMain.mark.setCategory(Cat.CAM_WEST);
     54                                SmedAction.panelMain.mark.setObjColour(Col.YELLOW);
     55                                SmedAction.panelMain.mark.addObjColour(Col.BLACK);
     56                                SmedAction.panelMain.mark.addObjColour(Col.YELLOW);
    5757                                westButton.setBorderPainted(true);
    5858                        } else {
     
    6060                        }
    6161                        if (isolButton.isSelected()) {
    62                                 dlg.panelMain.mark.setCategory(Cat.NOCAT);
    63                                 dlg.panelMain.mark.setObjColour(Col.BLACK);
    64                                 dlg.panelMain.mark.addObjColour(Col.RED);
    65                                 dlg.panelMain.mark.addObjColour(Col.BLACK);
     62                                SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
     63                                SmedAction.panelMain.mark.setObjColour(Col.BLACK);
     64                                SmedAction.panelMain.mark.addObjColour(Col.RED);
     65                                SmedAction.panelMain.mark.addObjColour(Col.BLACK);
    6666                                isolButton.setBorderPainted(true);
    6767                        } else {
    6868                                isolButton.setBorderPainted(false);
    6969                        }
    70                         topmarkButton.setVisible(dlg.panelMain.mark.testValid());
    71                         lightButton.setVisible(dlg.panelMain.mark.testValid());
    72                         dlg.panelMain.panelMore.syncPanel();
     70                        topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
     71                        lightButton.setVisible(SmedAction.panelMain.mark.testValid());
     72                        SmedAction.panelMain.panelMore.syncPanel();
    7373                }
    7474        };
     
    9090                                JRadioButton button = shapes.get(shp);
    9191                                if (button.isSelected()) {
    92                                         dlg.panelMain.mark.setShape(shp);
     92                                        SmedAction.panelMain.mark.setShape(shp);
    9393                                        if (isolButton.isSelected())
    94                                                 dlg.panelMain.mark.setObject(isdObjects.get(shp));
     94                                                SmedAction.panelMain.mark.setObject(isdObjects.get(shp));
    9595                                        else
    96                                                 dlg.panelMain.mark.setObject(carObjects.get(shp));
     96                                                SmedAction.panelMain.mark.setObject(carObjects.get(shp));
    9797                                        button.setBorderPainted(true);
    9898                                } else
    9999                                        button.setBorderPainted(false);
    100100                        }
    101                         topmarkButton.setVisible(dlg.panelMain.mark.testValid());
    102                         lightButton.setVisible(dlg.panelMain.mark.testValid());
     101                        topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
     102                        lightButton.setVisible(SmedAction.panelMain.mark.testValid());
    103103                }
    104104        };
     
    107107                public void actionPerformed(java.awt.event.ActionEvent e) {
    108108                        if (topmarkButton.isSelected()) {
    109                                 dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
    110                                 dlg.panelMain.mark.setTopColour(Col.BLACK);
    111                                 switch (dlg.panelMain.mark.getCategory()) {
     109                                SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
     110                                SmedAction.panelMain.mark.setTopColour(Col.BLACK);
     111                                switch (SmedAction.panelMain.mark.getCategory()) {
    112112                                case CAM_NORTH:
    113                                         dlg.panelMain.mark.setTopmark(Top.NORTH);
     113                                        SmedAction.panelMain.mark.setTopmark(Top.NORTH);
    114114                                        break;
    115115                                case CAM_SOUTH:
    116                                         dlg.panelMain.mark.setTopmark(Top.SOUTH);
     116                                        SmedAction.panelMain.mark.setTopmark(Top.SOUTH);
    117117                                        break;
    118118                                case CAM_EAST:
    119                                         dlg.panelMain.mark.setTopmark(Top.EAST);
     119                                        SmedAction.panelMain.mark.setTopmark(Top.EAST);
    120120                                        break;
    121121                                case CAM_WEST:
    122                                         dlg.panelMain.mark.setTopmark(Top.WEST);
     122                                        SmedAction.panelMain.mark.setTopmark(Top.WEST);
    123123                                        break;
    124124                                default:
    125                                         dlg.panelMain.mark.setTopmark(Top.SPHERES2);
     125                                        SmedAction.panelMain.mark.setTopmark(Top.SPHERES2);
    126126                                        break;
    127127                                }
    128128                                topmarkButton.setBorderPainted(true);
    129129                        } else {
    130                                 dlg.panelMain.mark.setTopmark(Top.NOTOP);
    131                                 dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
    132                                 dlg.panelMain.mark.setTopColour(Col.UNKCOL);
     130                                SmedAction.panelMain.mark.setTopmark(Top.NOTOP);
     131                                SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
     132                                SmedAction.panelMain.mark.setTopColour(Col.UNKCOL);
    133133                                topmarkButton.setBorderPainted(false);
    134134                        }
    135                         dlg.panelMain.panelTop.syncPanel();
     135                        SmedAction.panelMain.panelTop.syncPanel();
    136136                }
    137137        };
     
    140140                public void actionPerformed(java.awt.event.ActionEvent e) {
    141141                        if (lightButton.isSelected()) {
    142                                 dlg.panelMain.mark.setLightAtt(Att.COL, 0, Col.WHITE);
    143                                 switch (dlg.panelMain.mark.getCategory()) {
     142                                SmedAction.panelMain.mark.setLightAtt(Att.COL, 0, Col.WHITE);
     143                                switch (SmedAction.panelMain.mark.getCategory()) {
    144144                                case CAM_NORTH:
    145                                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
    146                                         dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "");
     145                                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
     146                                        SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "");
    147147                                        break;
    148148                                case CAM_SOUTH:
    149                                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q+LFl");
    150                                         dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "6");
     149                                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q+LFl");
     150                                        SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "6");
    151151                                        break;
    152152                                case CAM_EAST:
    153                                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
    154                                         dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "3");
     153                                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
     154                                        SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "3");
    155155                                        break;
    156156                                case CAM_WEST:
    157                                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
    158                                         dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "9");
     157                                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Q");
     158                                        SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "9");
    159159                                        break;
    160160                                default:
    161                                         dlg.panelMain.mark.setLightAtt(Att.CHR, 0, "Fl");
    162                                         dlg.panelMain.mark.setLightAtt(Att.GRP, 0, "2");
     161                                        SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, "Fl");
     162                                        SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, "2");
    163163                                        break;
    164164                                }
    165165                                lightButton.setBorderPainted(true);
    166166                        } else {
    167                                 dlg.panelMain.mark.clrLight();
     167                                SmedAction.panelMain.mark.clrLight();
    168168                                lightButton.setBorderPainted(false);
    169169                        }
    170                         dlg.panelMain.panelLit.syncPanel();
     170                        SmedAction.panelMain.panelLit.syncPanel();
    171171                }
    172172        };
     
    205205
    206206        public void syncPanel() {
    207                 northButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_NORTH);
    208                 southButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_SOUTH);
    209                 eastButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_EAST);
    210                 westButton.setBorderPainted(dlg.panelMain.mark.getCategory() == Cat.CAM_WEST);
    211                 isolButton.setBorderPainted(SeaMark.GrpMAP.get(dlg.panelMain.mark.getObject()) == Grp.ISD);
     207                northButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_NORTH);
     208                southButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_SOUTH);
     209                eastButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_EAST);
     210                westButton.setBorderPainted(SmedAction.panelMain.mark.getCategory() == Cat.CAM_WEST);
     211                isolButton.setBorderPainted(SeaMark.GrpMAP.get(SmedAction.panelMain.mark.getObject()) == Grp.ISD);
    212212                for (Shp shp : shapes.keySet()) {
    213213                        JRadioButton button = shapes.get(shp);
    214                         button.setBorderPainted(dlg.panelMain.mark.getShape() == shp);
    215                 }
    216                 topmarkButton.setBorderPainted(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
    217                 topmarkButton.setSelected(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
    218                 topmarkButton.setVisible(dlg.panelMain.mark.testValid());
    219                 Boolean lit = (dlg.panelMain.mark.getLightAtt(Att.COL, 0) != Col.UNKCOL) && !((String)dlg.panelMain.mark.getLightAtt(Att.CHR, 0)).isEmpty();
     214                        button.setBorderPainted(SmedAction.panelMain.mark.getShape() == shp);
     215                }
     216                topmarkButton.setBorderPainted(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
     217                topmarkButton.setSelected(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
     218                topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
     219                Boolean lit = (SmedAction.panelMain.mark.getLightAtt(Att.COL, 0) != Col.UNKCOL) && !((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, 0)).isEmpty();
    220220                lightButton.setBorderPainted(lit);
    221221                lightButton.setSelected(lit);
    222                 lightButton.setVisible(dlg.panelMain.mark.testValid());
     222                lightButton.setVisible(SmedAction.panelMain.mark.testValid());
    223223        }
    224224
  • applications/editors/josm/plugins/smed/src/panels/PanelLights.java

    r30737 r30738  
    2525                                int idx = landCats.get(cat);
    2626                                if (dlg.node != null && (idx == landCatBox.getSelectedIndex())) {
    27                                         dlg.panelMain.mark.setCategory(cat);
    28                                         dlg.panelMain.mark.testValid();
     27                                        SmedAction.panelMain.mark.setCategory(cat);
     28                                        SmedAction.panelMain.mark.testValid();
    2929                                }
    3030                        }
     
    3838                                int idx = trafficCats.get(cat);
    3939                                if (dlg.node != null && (idx == trafficCatBox.getSelectedIndex())) {
    40                                         dlg.panelMain.mark.setCategory(cat);
    41                                         dlg.panelMain.mark.testValid();
     40                                        SmedAction.panelMain.mark.setCategory(cat);
     41                                        SmedAction.panelMain.mark.testValid();
    4242                                }
    4343                        }
     
    5151                                int idx = warningCats.get(cat);
    5252                                if (dlg.node != null && (idx == warningCatBox.getSelectedIndex())) {
    53                                         dlg.panelMain.mark.setCategory(cat);
    54                                         dlg.panelMain.mark.testValid();
     53                                        SmedAction.panelMain.mark.setCategory(cat);
     54                                        SmedAction.panelMain.mark.testValid();
    5555                                }
    5656                        }
     
    6464                                int idx = platformCats.get(cat);
    6565                                if (dlg.node != null && (idx == platformCatBox.getSelectedIndex())) {
    66                                         dlg.panelMain.mark.setCategory(cat);
    67                                         dlg.panelMain.mark.testValid();
     66                                        SmedAction.panelMain.mark.setCategory(cat);
     67                                        SmedAction.panelMain.mark.testValid();
    6868                                }
    6969                        }
     
    7777                                int idx = pilotCats.get(cat);
    7878                                if (dlg.node != null && (idx == pilotCatBox.getSelectedIndex())) {
    79                                         dlg.panelMain.mark.setCategory(cat);
    80                                         dlg.panelMain.mark.testValid();
     79                                        SmedAction.panelMain.mark.setCategory(cat);
     80                                        SmedAction.panelMain.mark.testValid();
    8181                                }
    8282                        }
     
    9090                                int idx = rescueCats.get(cat);
    9191                                if (dlg.node != null && (idx == rescueCatBox.getSelectedIndex())) {
    92                                         dlg.panelMain.mark.setCategory(cat);
    93                                         dlg.panelMain.mark.testValid();
     92                                        SmedAction.panelMain.mark.setCategory(cat);
     93                                        SmedAction.panelMain.mark.testValid();
    9494                                }
    9595                        }
     
    103103                                int idx = radioCats.get(cat);
    104104                                if (dlg.node != null && (idx == radioCatBox.getSelectedIndex())) {
    105                                         dlg.panelMain.mark.setCategory(cat);
    106                                         dlg.panelMain.mark.testValid();
     105                                        SmedAction.panelMain.mark.setCategory(cat);
     106                                        SmedAction.panelMain.mark.testValid();
    107107                                }
    108108                        }
     
    116116                                int idx = radarCats.get(cat);
    117117                                if (dlg.node != null && (idx == radarCatBox.getSelectedIndex())) {
    118                                         dlg.panelMain.mark.setCategory(cat);
    119                                         dlg.panelMain.mark.testValid();
     118                                        SmedAction.panelMain.mark.setCategory(cat);
     119                                        SmedAction.panelMain.mark.testValid();
    120120                                }
    121121                        }
     
    130130                                int idx = functions.get(fnc);
    131131                                if (dlg.node != null && (idx == functionBox.getSelectedIndex())) {
    132                                         dlg.panelMain.mark.setFunc(fnc);
    133                                         dlg.panelMain.mark.testValid();
     132                                        SmedAction.panelMain.mark.setFunc(fnc);
     133                                        SmedAction.panelMain.mark.testValid();
    134134                                }
    135135                        }
     
    157157                                JRadioButton button = objects.get(obj);
    158158                                if (button.isSelected()) {
    159                                         dlg.panelMain.mark.setObject(obj);
     159                                        SmedAction.panelMain.mark.setObject(obj);
    160160                                        button.setBorderPainted(true);
    161161                                } else
    162162                                        button.setBorderPainted(false);
    163163                        }
    164                         if (dlg.panelMain.mark.getObject() == Obj.LITVES)
    165                                 dlg.panelMain.mark.setShape(Shp.SUPER);
    166                         else if (dlg.panelMain.mark.getObject() == Obj.LITFLT)
    167                                 dlg.panelMain.mark.setShape(Shp.FLOAT);
    168                         else dlg.panelMain.mark.setShape(Shp.UNKSHP);
     164                        if (SmedAction.panelMain.mark.getObject() == Obj.LITVES)
     165                                SmedAction.panelMain.mark.setShape(Shp.SUPER);
     166                        else if (SmedAction.panelMain.mark.getObject() == Obj.LITFLT)
     167                                SmedAction.panelMain.mark.setShape(Shp.FLOAT);
     168                        else SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    169169                        functionLabel.setVisible(false);
    170170                        categoryLabel.setVisible(false);
     
    181181                        chLabel.setVisible(false);
    182182                        chBox.setVisible(false);
    183                         dlg.panelMain.mark.setCategory(Cat.NOCAT);
     183                        SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
    184184                        if (landButton.isSelected()) {
    185185                                functionLabel.setVisible(true);
     
    227227                                alRadarCatBox.actionPerformed(null);
    228228                        }
    229                         dlg.panelMain.mark.testValid();
     229                        SmedAction.panelMain.mark.testValid();
    230230                }
    231231        };
     
    234234        private FocusListener flCh = new FocusAdapter() {
    235235                public void focusLost(java.awt.event.FocusEvent e) {
    236                         dlg.panelMain.mark.setChannel(chBox.getText());
     236                        SmedAction.panelMain.mark.setChannel(chBox.getText());
    237237                }
    238238        };
     
    462462                chLabel.setVisible(false);
    463463                chBox.setVisible(false);
    464                 chBox.setText(dlg.panelMain.mark.getChannel());
    465                 if ((dlg.panelMain.mark.getObject() == Obj.LNDMRK) && ((dlg.panelMain.mark.getCategory() != Cat.NOCAT) || (dlg.panelMain.mark.getFunc() != Fnc.UNKFNC))) {
     464                chBox.setText(SmedAction.panelMain.mark.getChannel());
     465                if ((SmedAction.panelMain.mark.getObject() == Obj.LNDMRK) && ((SmedAction.panelMain.mark.getCategory() != Cat.NOCAT) || (SmedAction.panelMain.mark.getFunc() != Fnc.UNKFNC))) {
    466466                        functionLabel.setVisible(true);
    467467                        categoryLabel.setVisible(true);
     
    470470                        for (Fnc fnc : functions.keySet()) {
    471471                                int item = functions.get(fnc);
    472                                 if (dlg.panelMain.mark.getFunc() == fnc)
     472                                if (SmedAction.panelMain.mark.getFunc() == fnc)
    473473                                        functionBox.setSelectedIndex(item);
    474474                        }
    475475                        for (Cat cat : landCats.keySet()) {
    476476                                int item = landCats.get(cat);
    477                                 if (dlg.panelMain.mark.getCategory() == cat)
     477                                if (SmedAction.panelMain.mark.getCategory() == cat)
    478478                                        landCatBox.setSelectedIndex(item);
    479479                        }
    480                 } else if (dlg.panelMain.mark.getObject() == Obj.SISTAT) {
     480                } else if (SmedAction.panelMain.mark.getObject() == Obj.SISTAT) {
    481481                                categoryLabel.setVisible(true);
    482482                                trafficCatBox.setVisible(true);
    483483                                for (Cat cat : trafficCats.keySet()) {
    484484                                        int item = trafficCats.get(cat);
    485                                         if (dlg.panelMain.mark.getCategory() == cat)
     485                                        if (SmedAction.panelMain.mark.getCategory() == cat)
    486486                                                trafficCatBox.setSelectedIndex(item);
    487487                                }
    488488                                chLabel.setVisible(true);
    489489                                chBox.setVisible(true);
    490                 } else if (dlg.panelMain.mark.getObject() == Obj.SISTAW) {
     490                } else if (SmedAction.panelMain.mark.getObject() == Obj.SISTAW) {
    491491                        categoryLabel.setVisible(true);
    492492                        warningCatBox.setVisible(true);
    493493                        for (Cat cat : warningCats.keySet()) {
    494494                                int item = warningCats.get(cat);
    495                                 if (dlg.panelMain.mark.getCategory() == cat)
     495                                if (SmedAction.panelMain.mark.getCategory() == cat)
    496496                                        warningCatBox.setSelectedIndex(item);
    497497                        }
    498498                        chLabel.setVisible(true);
    499499                        chBox.setVisible(true);
    500                 } else if (dlg.panelMain.mark.getObject() == Obj.OFSPLF) {
     500                } else if (SmedAction.panelMain.mark.getObject() == Obj.OFSPLF) {
    501501                        categoryLabel.setVisible(true);
    502502                        platformCatBox.setVisible(true);
    503503                        for (Cat cat : platformCats.keySet()) {
    504504                                int item = platformCats.get(cat);
    505                                 if (dlg.panelMain.mark.getCategory() == cat)
     505                                if (SmedAction.panelMain.mark.getCategory() == cat)
    506506                                        platformCatBox.setSelectedIndex(item);
    507507                        }
    508                 } else if (dlg.panelMain.mark.getObject() == Obj.PILBOP) {
     508                } else if (SmedAction.panelMain.mark.getObject() == Obj.PILBOP) {
    509509                        categoryLabel.setVisible(true);
    510510                        pilotCatBox.setVisible(true);
    511511                        for (Cat cat : pilotCats.keySet()) {
    512512                                int item = pilotCats.get(cat);
    513                                 if (dlg.panelMain.mark.getCategory() == cat)
     513                                if (SmedAction.panelMain.mark.getCategory() == cat)
    514514                                        pilotCatBox.setSelectedIndex(item);
    515515                        }
    516516                        chLabel.setVisible(true);
    517517                        chBox.setVisible(true);
    518                 } else if (dlg.panelMain.mark.getObject() == Obj.RSCSTA) {
     518                } else if (SmedAction.panelMain.mark.getObject() == Obj.RSCSTA) {
    519519                        categoryLabel.setVisible(true);
    520520                        rescueCatBox.setVisible(true);
    521521                        for (Cat cat : rescueCats.keySet()) {
    522522                                int item = rescueCats.get(cat);
    523                                 if (dlg.panelMain.mark.getCategory() == cat)
     523                                if (SmedAction.panelMain.mark.getCategory() == cat)
    524524                                        rescueCatBox.setSelectedIndex(item);
    525525                        }
    526                 } else if (dlg.panelMain.mark.getObject() == Obj.RDOSTA) {
     526                } else if (SmedAction.panelMain.mark.getObject() == Obj.RDOSTA) {
    527527                        categoryLabel.setVisible(true);
    528528                        radioCatBox.setVisible(true);
    529529                        for (Cat cat : radioCats.keySet()) {
    530530                                int item = radioCats.get(cat);
    531                                 if (dlg.panelMain.mark.getCategory() == cat)
     531                                if (SmedAction.panelMain.mark.getCategory() == cat)
    532532                                        radioCatBox.setSelectedIndex(item);
    533533                        }
    534534                        chLabel.setVisible(true);
    535535                        chBox.setVisible(true);
    536                 } else if (dlg.panelMain.mark.getObject() == Obj.RADSTA) {
     536                } else if (SmedAction.panelMain.mark.getObject() == Obj.RADSTA) {
    537537                        categoryLabel.setVisible(true);
    538538                        radarCatBox.setVisible(true);
    539539                        for (Cat cat : radarCats.keySet()) {
    540540                                int item = radarCats.get(cat);
    541                                 if (dlg.panelMain.mark.getCategory() == cat)
     541                                if (SmedAction.panelMain.mark.getCategory() == cat)
    542542                                        radarCatBox.setSelectedIndex(item);
    543543                        }
     
    547547                for (Obj obj : objects.keySet()) {
    548548                        JRadioButton button = objects.get(obj);
    549                         button.setBorderPainted(dlg.panelMain.mark.getObject() == obj);
    550                 }
    551                 dlg.panelMain.mark.testValid();
     549                        button.setBorderPainted(SmedAction.panelMain.mark.getObject() == obj);
     550                }
     551                SmedAction.panelMain.mark.testValid();
    552552        }
    553553       
  • applications/editors/josm/plugins/smed/src/panels/PanelLit.java

    r30737 r30738  
    2121        private FocusListener flGroup = new FocusAdapter() {
    2222                public void focusLost(java.awt.event.FocusEvent e) {
    23                         dlg.panelMain.mark.setLightAtt(Att.GRP, 0, groupBox.getText());
     23                        SmedAction.panelMain.mark.setLightAtt(Att.GRP, 0, groupBox.getText());
    2424                }
    2525        };
     
    2828        private FocusListener flPeriod = new FocusAdapter() {
    2929                public void focusLost(java.awt.event.FocusEvent e) {
    30                         dlg.panelMain.mark.setLightAtt(Att.PER, 0, periodBox.getText());
     30                        SmedAction.panelMain.mark.setLightAtt(Att.PER, 0, periodBox.getText());
    3131                }
    3232        };
     
    3535        private FocusListener flSequence = new FocusAdapter() {
    3636                public void focusLost(java.awt.event.FocusEvent e) {
    37                         dlg.panelMain.mark.setLightAtt(Att.SEQ, 0, sequenceBox.getText());
     37                        SmedAction.panelMain.mark.setLightAtt(Att.SEQ, 0, sequenceBox.getText());
    3838                }
    3939        };
     
    4646                                int idx = visibilities.get(vis);
    4747                                if (idx == visibilityBox.getSelectedIndex())
    48                                         dlg.panelMain.mark.setLightAtt(Att.VIS, 0, vis);
     48                                        SmedAction.panelMain.mark.setLightAtt(Att.VIS, 0, vis);
    4949                        }
    5050                }
     
    5454        private FocusListener flHeight = new FocusAdapter() {
    5555                public void focusLost(java.awt.event.FocusEvent e) {
    56                         dlg.panelMain.mark.setLightAtt(Att.HGT, 0, heightBox.getText());
     56                        SmedAction.panelMain.mark.setLightAtt(Att.HGT, 0, heightBox.getText());
    5757                }
    5858        };
     
    6161        private FocusListener flRange = new FocusAdapter() {
    6262                public void focusLost(java.awt.event.FocusEvent e) {
    63                         dlg.panelMain.mark.setLightAtt(Att.RNG, 0, rangeBox.getText());
     63                        SmedAction.panelMain.mark.setLightAtt(Att.RNG, 0, rangeBox.getText());
    6464                }
    6565        };
     
    6868        private FocusListener flOrientation = new FocusAdapter() {
    6969                public void focusLost(java.awt.event.FocusEvent e) {
    70                         dlg.panelMain.mark.setLightAtt(Att.ORT, 0, orientationBox.getText());
     70                        SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, orientationBox.getText());
    7171                }
    7272        };
     
    7575        private FocusListener flMultiple = new FocusAdapter() {
    7676                public void focusLost(java.awt.event.FocusEvent e) {
    77                         dlg.panelMain.mark.setLightAtt(Att.MLT, 0, multipleBox.getText());
     77                        SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, multipleBox.getText());
    7878                }
    7979        };
     
    8686                                int idx = categories.get(lit);
    8787                                if (idx == categoryBox.getSelectedIndex())
    88                                         dlg.panelMain.mark.setLightAtt(Att.LIT, 0, lit);
    89                         }
    90                         if (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR) {
    91                                 dlg.panelMain.mark.setLightAtt(Att.MLT, 0, "");
     88                                        SmedAction.panelMain.mark.setLightAtt(Att.LIT, 0, lit);
     89                        }
     90                        if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR) {
     91                                SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, "");
    9292                                multipleBox.setText("");
    9393                                orientationLabel.setVisible(true);
     
    9595                                multipleLabel.setVisible(false);
    9696                                multipleBox.setVisible(false);
    97                         } else if ((dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ)) {
    98                                 dlg.panelMain.mark.setLightAtt(Att.ORT, 0, "");
     97                        } else if ((SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ)) {
     98                                SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, "");
    9999                                orientationBox.setText("");
    100100                                orientationLabel.setVisible(false);
     
    103103                                multipleBox.setVisible(true);
    104104                        } else {
    105                                 dlg.panelMain.mark.setLightAtt(Att.MLT, 0, "");
     105                                SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, "");
    106106                                multipleBox.setText("");
    107                                 dlg.panelMain.mark.setLightAtt(Att.ORT, 0, "");
     107                                SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, "");
    108108                                orientationBox.setText("");
    109109                                orientationLabel.setVisible(false);
     
    122122                                int idx = exhibitions.get(exh);
    123123                                if (idx == exhibitionBox.getSelectedIndex())
    124                                         dlg.panelMain.mark.setLightAtt(Att.EXH, 0, exh);
     124                                        SmedAction.panelMain.mark.setLightAtt(Att.EXH, 0, exh);
    125125                        }
    126126                }
     
    137137                        } else {
    138138                                panelSector.setVisible(false);
    139                                 while (dlg.panelMain.mark.getSectorCount() > 1)
    140                                         dlg.panelMain.mark.delLight(1);
     139                                while (SmedAction.panelMain.mark.getSectorCount() > 1)
     140                                        SmedAction.panelMain.mark.delLight(1);
    141141                        }
    142142                }
     
    285285                multipleLabel.setVisible(false);
    286286                multipleBox.setVisible(false);
    287                 groupBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.GRP, 0));
    288                 periodBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.PER, 0));
    289                 sequenceBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.SEQ, 0));
    290                 heightBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.HGT, 0));
    291                 rangeBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.RNG, 0));
    292                 orientationBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.ORT, 0));
    293                 orientationBox.setVisible(dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR);
    294                 multipleBox.setText((String)dlg.panelMain.mark.getLightAtt(Att.MLT, 0));
    295                 multipleBox.setVisible((dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ));
     287                groupBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.GRP, 0));
     288                periodBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.PER, 0));
     289                sequenceBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.SEQ, 0));
     290                heightBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.HGT, 0));
     291                rangeBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.RNG, 0));
     292                orientationBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.ORT, 0));
     293                orientationBox.setVisible(SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.DIR);
     294                multipleBox.setText((String)SmedAction.panelMain.mark.getLightAtt(Att.MLT, 0));
     295                multipleBox.setVisible((SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.VERT) || (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == Lit.HORIZ));
    296296                for (Vis vis : visibilities.keySet()) {
    297297                        int item = visibilities.get(vis);
    298                         if (dlg.panelMain.mark.getLightAtt(Att.VIS, 0) == vis)
     298                        if (SmedAction.panelMain.mark.getLightAtt(Att.VIS, 0) == vis)
    299299                                visibilityBox.setSelectedIndex(item);
    300300                }
    301301                for (Lit lit : categories.keySet()) {
    302302                        int item = categories.get(lit);
    303                         if (dlg.panelMain.mark.getLightAtt(Att.LIT, 0) == lit)
     303                        if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, 0) == lit)
    304304                                categoryBox.setSelectedIndex(item);
    305305                }
    306306                for (Exh exh : exhibitions.keySet()) {
    307307                        int item = exhibitions.get(exh);
    308                         if (dlg.panelMain.mark.getLightAtt(Att.EXH, 0) == exh)
     308                        if (SmedAction.panelMain.mark.getLightAtt(Att.EXH, 0) == exh)
    309309                                exhibitionBox.setSelectedIndex(item);
    310310                }
    311                 if (dlg.panelMain.mark.isSectored()) {
     311                if (SmedAction.panelMain.mark.isSectored()) {
    312312                        singleButton.setBorderPainted(false);
    313313                        sectorButton.setBorderPainted(true);
     
    317317                        sectorButton.setBorderPainted(false);
    318318                        panelSector.setVisible(false);
    319                         while (dlg.panelMain.mark.getSectorCount() > 1)
    320                                 dlg.panelMain.mark.delLight(dlg.panelMain.mark.getSectorCount() - 1);
     319                        while (SmedAction.panelMain.mark.getSectorCount() > 1)
     320                                SmedAction.panelMain.mark.delLight(SmedAction.panelMain.mark.getSectorCount() - 1);
    321321                }
    322322                panelCol.syncPanel();
  • applications/editors/josm/plugins/smed/src/panels/PanelMore.java

    r30737 r30738  
    1919        private FocusListener flInfo = new FocusAdapter() {
    2020                public void focusLost(java.awt.event.FocusEvent e) {
    21                         dlg.panelMain.mark.setInfo(infoBox.getText());
     21                        SmedAction.panelMain.mark.setInfo(infoBox.getText());
    2222                }
    2323        };
     
    2626        private FocusListener flSource = new FocusAdapter() {
    2727                public void focusLost(java.awt.event.FocusEvent e) {
    28                         dlg.panelMain.mark.setSource(sourceBox.getText());
     28                        SmedAction.panelMain.mark.setSource(sourceBox.getText());
    2929                }
    3030        };
     
    3333        private FocusListener flElev = new FocusAdapter() {
    3434                public void focusLost(java.awt.event.FocusEvent e) {
    35                         dlg.panelMain.mark.setElevation(elevBox.getText());
     35                        SmedAction.panelMain.mark.setElevation(elevBox.getText());
    3636                }
    3737        };
     
    4040        private FocusListener flHeight = new FocusAdapter() {
    4141                public void focusLost(java.awt.event.FocusEvent e) {
    42                         dlg.panelMain.mark.setObjectHeight(heightBox.getText());
     42                        SmedAction.panelMain.mark.setObjectHeight(heightBox.getText());
    4343                }
    4444        };
     
    5050                        for (Sts sts : statuses.keySet()) {
    5151                                int idx = statuses.get(sts);
    52                                 if (dlg.panelMain.mark != null && (idx == statusBox.getSelectedIndex()))
    53                                         dlg.panelMain.mark.setStatus(sts);
     52                                if (SmedAction.panelMain.mark != null && (idx == statusBox.getSelectedIndex()))
     53                                        SmedAction.panelMain.mark.setStatus(sts);
    5454                        }
    5555                }
     
    6262                        for (Cns cns : constructions.keySet()) {
    6363                                int idx = constructions.get(cns);
    64                                 if (dlg.panelMain.mark != null && (idx == constrBox.getSelectedIndex()))
    65                                         dlg.panelMain.mark.setConstr(cns);
     64                                if (SmedAction.panelMain.mark != null && (idx == constrBox.getSelectedIndex()))
     65                                        SmedAction.panelMain.mark.setConstr(cns);
    6666                        }
    6767                }
     
    7474                        for (Con con : conspicuities.keySet()) {
    7575                                int idx = conspicuities.get(con);
    76                                 if (dlg.panelMain.mark != null && (idx == conBox.getSelectedIndex()))
    77                                         dlg.panelMain.mark.setConsp(con);
     76                                if (SmedAction.panelMain.mark != null && (idx == conBox.getSelectedIndex()))
     77                                        SmedAction.panelMain.mark.setConsp(con);
    7878                        }
    7979                }
     
    8686                        for (Con con : reflectivities.keySet()) {
    8787                                int idx = reflectivities.get(con);
    88                                 if (dlg.panelMain.mark != null && (idx == reflBox.getSelectedIndex()))
    89                                         dlg.panelMain.mark.setRefl(con);
     88                                if (SmedAction.panelMain.mark != null && (idx == reflBox.getSelectedIndex()))
     89                                        SmedAction.panelMain.mark.setRefl(con);
    9090                        }
    9191                }
     
    9999                public void actionPerformed(java.awt.event.ActionEvent e) {
    100100                        if (regionAButton.isSelected()) {
    101                                 dlg.panelMain.mark.setRegion(Reg.A);
     101                                SmedAction.panelMain.mark.setRegion(Reg.A);
    102102                                switch (dlg.panelMain.mark.getCategory()) {
    103103                                case LAM_PORT:
  • applications/editors/josm/plugins/smed/src/panels/PanelPat.java

    r30737 r30738  
    3131                                JRadioButton button = patterns.get(pat);
    3232                                if (button.isSelected()) {
    33                                         dlg.panelMain.mark.setPattern(ent, pat);
     33                                        SmedAction.panelMain.mark.setPattern(ent, pat);
    3434                                        button.setBorderPainted(true);
    3535                                } else
    3636                                        button.setBorderPainted(false);
    3737                        }
    38                         switch (dlg.panelMain.mark.getPattern(ent)) {
     38                        switch (SmedAction.panelMain.mark.getPattern(ent)) {
    3939                        case NOPAT:
    4040                                panelCol.trimStack(1);
     
    7474                for (Pat pat : patterns.keySet()) {
    7575                        JRadioButton button = patterns.get(pat);
    76                         if (dlg.panelMain.mark.getPattern(ent) == pat) {
     76                        if (SmedAction.panelMain.mark.getPattern(ent) == pat) {
    7777                                button.setBorderPainted(true);
    7878                        } else
  • applications/editors/josm/plugins/smed/src/panels/PanelPort.java

    r30737 r30738  
    3131                                JRadioButton button = shapes.get(shp);
    3232                                if (button.isSelected()) {
    33                                         dlg.panelMain.mark.setShape(shp);
    34                                         dlg.panelMain.mark.setObject(objects.get(shp));
     33                                        SmedAction.panelMain.mark.setShape(shp);
     34                                        SmedAction.panelMain.mark.setObject(objects.get(shp));
    3535                                        button.setBorderPainted(true);
    3636                                } else
    3737                                        button.setBorderPainted(false);
    3838                        }
    39                         if (dlg.panelMain.mark.testValid()) {
    40                                 dlg.panelMain.panelChan.topmarkButton.setVisible(true);
    41                                 dlg.panelMain.panelChan.lightButton.setVisible(true);
    42                                 if (dlg.panelMain.mark.getCategory() == Cat.LAM_PORT) {
    43                                         switch (dlg.panelMain.mark.getRegion()) {
     39                        if (SmedAction.panelMain.mark.testValid()) {
     40                                SmedAction.panelMain.panelChan.topmarkButton.setVisible(true);
     41                                SmedAction.panelMain.panelChan.lightButton.setVisible(true);
     42                                if (SmedAction.panelMain.mark.getCategory() == Cat.LAM_PORT) {
     43                                        switch (SmedAction.panelMain.mark.getRegion()) {
    4444                                        case A:
    45                                                 dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
    46                                                 dlg.panelMain.mark.setObjColour(Col.RED);
     45                                                SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
     46                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
    4747                                                break;
    4848                                        case B:
    49                                                 dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
    50                                                 dlg.panelMain.mark.setObjColour(Col.GREEN);
     49                                                SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
     50                                                SmedAction.panelMain.mark.setObjColour(Col.GREEN);
    5151                                                break;
    5252                                        case C:
    53                                                 dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
    54                                                 dlg.panelMain.mark.setObjColour(Col.RED);
    55                                                 dlg.panelMain.mark.addObjColour(Col.WHITE);
    56                                                 dlg.panelMain.mark.addObjColour(Col.RED);
    57                                                 dlg.panelMain.mark.addObjColour(Col.WHITE);
     53                                                SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
     54                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
     55                                                SmedAction.panelMain.mark.addObjColour(Col.WHITE);
     56                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
     57                                                SmedAction.panelMain.mark.addObjColour(Col.WHITE);
    5858                                                break;
    5959                                        }
    6060                                } else {
    61                                         dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
    62                                         switch (dlg.panelMain.mark.getRegion()) {
     61                                        SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
     62                                        switch (SmedAction.panelMain.mark.getRegion()) {
    6363                                        case A:
    64                                                 dlg.panelMain.mark.setObjColour(Col.RED);
    65                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
    66                                                 dlg.panelMain.mark.addObjColour(Col.RED);
     64                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
     65                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
     66                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
    6767                                                break;
    6868                                        case B:
    69                                                 dlg.panelMain.mark.setObjColour(Col.GREEN);
    70                                                 dlg.panelMain.mark.addObjColour(Col.RED);
    71                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
     69                                                SmedAction.panelMain.mark.setObjColour(Col.GREEN);
     70                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
     71                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
    7272                                                break;
    7373                                        case C:
    74                                                 dlg.panelMain.mark.setObjColour(Col.RED);
    75                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
    76                                                 dlg.panelMain.mark.addObjColour(Col.RED);
    77                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
     74                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
     75                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
     76                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
     77                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
    7878                                                break;
    7979                                        }
    8080                                }
    81                                 dlg.panelMain.panelMore.syncPanel();
     81                                SmedAction.panelMain.panelMore.syncPanel();
    8282                        } else {
    83                                 dlg.panelMain.panelChan.topmarkButton.setVisible(false);
    84                                 dlg.panelMain.panelChan.lightButton.setVisible(false);
     83                                SmedAction.panelMain.panelChan.topmarkButton.setVisible(false);
     84                                SmedAction.panelMain.panelChan.lightButton.setVisible(false);
    8585                        }
    8686                }
     
    104104                for (Shp shp : shapes.keySet()) {
    105105                        JRadioButton button = shapes.get(shp);
    106                         if (dlg.panelMain.mark.getShape() == shp) {
     106                        if (SmedAction.panelMain.mark.getShape() == shp) {
    107107                                button.setBorderPainted(true);
    108108                        } else
  • applications/editors/josm/plugins/smed/src/panels/PanelRadar.java

    r30737 r30738  
    3535                                int idx = radioCats.get(cat);
    3636                                if (dlg.node != null && (idx == radioCatBox.getSelectedIndex())) {
    37                                         dlg.panelMain.mark.setRadio(cat);
     37                                        SmedAction.panelMain.mark.setRadio(cat);
    3838                                }
    3939                        }
     
    5252                                JRadioButton button = rads.get(rtb);
    5353                                if (button.isSelected()) {
    54                                         dlg.panelMain.mark.setRadar(rtb);
     54                                        SmedAction.panelMain.mark.setRadar(rtb);
    5555                                }
    5656                        }
     
    6262        private FocusListener flGroup = new FocusAdapter() {
    6363                public void focusLost(java.awt.event.FocusEvent e) {
    64                         dlg.panelMain.mark.setRaconGroup(groupBox.getText());
     64                        SmedAction.panelMain.mark.setRaconGroup(groupBox.getText());
    6565                }
    6666        };
     
    6969        private FocusListener flPeriod = new FocusAdapter() {
    7070                public void focusLost(java.awt.event.FocusEvent e) {
    71                         dlg.panelMain.mark.setRaconPeriod(periodBox.getText());
     71                        SmedAction.panelMain.mark.setRaconPeriod(periodBox.getText());
    7272                }
    7373        };
     
    7676        private FocusListener flSeq = new FocusAdapter() {
    7777                public void focusLost(java.awt.event.FocusEvent e) {
    78                         dlg.panelMain.mark.setRaconSequence(seqBox.getText());
     78                        SmedAction.panelMain.mark.setRaconSequence(seqBox.getText());
    7979                }
    8080        };
     
    8383        private FocusListener flRange = new FocusAdapter() {
    8484                public void focusLost(java.awt.event.FocusEvent e) {
    85                         dlg.panelMain.mark.setRaconRange(rangeBox.getText());
     85                        SmedAction.panelMain.mark.setRaconRange(rangeBox.getText());
    8686                }
    8787        };
     
    9090        private FocusListener flSector1 = new FocusAdapter() {
    9191                public void focusLost(java.awt.event.FocusEvent e) {
    92                         dlg.panelMain.mark.setRaconSector1(sector1Box.getText());
     92                        SmedAction.panelMain.mark.setRaconSector1(sector1Box.getText());
    9393                }
    9494        };
     
    9797        private FocusListener flSector2 = new FocusAdapter() {
    9898                public void focusLost(java.awt.event.FocusEvent e) {
    99                         dlg.panelMain.mark.setRaconSector2(sector2Box.getText());
     99                        SmedAction.panelMain.mark.setRaconSector2(sector2Box.getText());
    100100                }
    101101        };
     
    204204
    205205        public void syncPanel() {
    206                 boolean rad = ((dlg.panelMain.mark.getRadar() != Rtb.NORTB) && (dlg.panelMain.mark.getRadar() != Rtb.REFLECTOR));
     206                boolean rad = ((SmedAction.panelMain.mark.getRadar() != Rtb.NORTB) && (SmedAction.panelMain.mark.getRadar() != Rtb.REFLECTOR));
    207207                groupLabel.setVisible(rad);
    208208                groupBox.setVisible(rad);
     
    219219                sectorsLabel.setVisible(rad);
    220220                for (Rtb rtb : rads.keySet()) {
    221                         rads.get(rtb).setBorderPainted(dlg.panelMain.mark.getRadar() == rtb);
    222                 }
    223                 groupBox.setText(dlg.panelMain.mark.getRaconGroup());
    224                 seqBox.setText(dlg.panelMain.mark.getRaconSequence());
    225                 periodBox.setText(dlg.panelMain.mark.getRaconPeriod());
    226                 rangeBox.setText(dlg.panelMain.mark.getRaconRange());
    227                 sector1Box.setText(dlg.panelMain.mark.getRaconSector1());
    228                 sector2Box.setText(dlg.panelMain.mark.getRaconSector2());
    229                 aisButton.setSelected(dlg.panelMain.mark.getRadio() != Cat.NOROS);
     221                        rads.get(rtb).setBorderPainted(SmedAction.panelMain.mark.getRadar() == rtb);
     222                }
     223                groupBox.setText(SmedAction.panelMain.mark.getRaconGroup());
     224                seqBox.setText(SmedAction.panelMain.mark.getRaconSequence());
     225                periodBox.setText(SmedAction.panelMain.mark.getRaconPeriod());
     226                rangeBox.setText(SmedAction.panelMain.mark.getRaconRange());
     227                sector1Box.setText(SmedAction.panelMain.mark.getRaconSector1());
     228                sector2Box.setText(SmedAction.panelMain.mark.getRaconSector2());
     229                aisButton.setSelected(SmedAction.panelMain.mark.getRadio() != Cat.NOROS);
    230230                aisButton.setBorderPainted(aisButton.isSelected());
    231                 radioCatBox.setVisible(dlg.panelMain.mark.getRadio() != Cat.NOROS);
     231                radioCatBox.setVisible(SmedAction.panelMain.mark.getRadio() != Cat.NOROS);
    232232        }
    233233
  • applications/editors/josm/plugins/smed/src/panels/PanelSaw.java

    r30737 r30738  
    2727                                JRadioButton button = shapes.get(shp);
    2828                                if (button.isSelected()) {
    29                                         dlg.panelMain.mark.setShape(shp);
    30                                         dlg.panelMain.mark.setObject(objects.get(shp));
     29                                        SmedAction.panelMain.mark.setShape(shp);
     30                                        SmedAction.panelMain.mark.setObject(objects.get(shp));
    3131                                        button.setBorderPainted(true);
    3232                                } else
    3333                                        button.setBorderPainted(false);
    3434                        }
    35                         if (dlg.panelMain.mark.testValid()) {
    36                                 dlg.panelMain.panelChan.topmarkButton.setVisible(true);
    37                                 dlg.panelMain.mark.setObjPattern(Pat.VSTRP);
    38                                 dlg.panelMain.mark.setObjColour(Col.RED);
    39                                 dlg.panelMain.mark.addObjColour(Col.WHITE);
     35                        if (SmedAction.panelMain.mark.testValid()) {
     36                                SmedAction.panelMain.panelChan.topmarkButton.setVisible(true);
     37                                SmedAction.panelMain.mark.setObjPattern(Pat.VSTRP);
     38                                SmedAction.panelMain.mark.setObjColour(Col.RED);
     39                                SmedAction.panelMain.mark.addObjColour(Col.WHITE);
    4040                        } else {
    41                                 dlg.panelMain.panelChan.topmarkButton.setVisible(false);
     41                                SmedAction.panelMain.panelChan.topmarkButton.setVisible(false);
    4242                        }
    43                         dlg.panelMain.panelMore.syncPanel();
     43                        SmedAction.panelMain.panelMore.syncPanel();
    4444                }
    4545        };
     
    5858                for (Shp shp : shapes.keySet()) {
    5959                        JRadioButton button = shapes.get(shp);
    60                         if (dlg.panelMain.mark.getShape() == shp) {
     60                        if (SmedAction.panelMain.mark.getShape() == shp) {
    6161                                button.setBorderPainted(true);
    6262                        } else
    6363                                button.setBorderPainted(false);
    6464                }
    65                 dlg.panelMain.mark.testValid();
     65                SmedAction.panelMain.mark.testValid();
    6666        }
    6767       
  • applications/editors/josm/plugins/smed/src/panels/PanelSectors.java

    r30737 r30738  
    123123
    124124                public int getRowCount() {
    125                         if (dlg.panelMain == null)
     125                        if (SmedAction.panelMain == null)
    126126                                return 1;
    127127                        else
    128                                 return dlg.panelMain.mark.getSectorCount();
     128                                return SmedAction.panelMain.mark.getSectorCount();
    129129                }
    130130
     
    152152                                        return row;
    153153                        case 1:
    154                                 if (((String)dlg.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
    155                                         if (dlg.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL) {
     154                                if (((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
     155                                        if (SmedAction.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL) {
    156156                                                return Col.UNKCOL;
    157157                                        } else {
    158                                                 return dlg.panelMain.mark.getLightAtt(Att.ALT, row);
     158                                                return SmedAction.panelMain.mark.getLightAtt(Att.ALT, row);
    159159                                        }
    160160                                } else {
    161                                         return dlg.panelMain.mark.getLightAtt(Att.COL, row);
     161                                        return SmedAction.panelMain.mark.getLightAtt(Att.COL, row);
    162162                                }
    163163                        case 6:
    164                                 return (dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR);
     164                                return (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR);
    165165                        case 7:
    166166                        case 8:
    167                                 if (dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR)
    168                                         return dlg.panelMain.mark.getLightAtt(Att.ORT, row);
     167                                if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR)
     168                                        return SmedAction.panelMain.mark.getLightAtt(Att.ORT, row);
    169169                                else
    170                                         return dlg.panelMain.mark.getLightAtt(col - 1, row);
     170                                        return SmedAction.panelMain.mark.getLightAtt(col - 1, row);
    171171                        case 12:
    172                                 return visibilities.get(dlg.panelMain.mark.getLightAtt(Att.VIS, row));
     172                                return visibilities.get(SmedAction.panelMain.mark.getLightAtt(Att.VIS, row));
    173173                        case 13:
    174                                 return exhibitions.get(dlg.panelMain.mark.getLightAtt(Att.EXH, row));
     174                                return exhibitions.get(SmedAction.panelMain.mark.getLightAtt(Att.EXH, row));
    175175                        default:
    176                                 return dlg.panelMain.mark.getLightAtt(col - 1, row);
     176                                return SmedAction.panelMain.mark.getLightAtt(col - 1, row);
    177177                        }
    178178                }
     
    184184                                        ImageIcon img = colours.get(colour);
    185185                                        if (img == value)
    186                                                 if (((String)dlg.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
    187                                                         if (((colour == Col.UNKCOL) && (dlg.panelMain.mark.getLightAtt(Att.ALT, row) == Col.UNKCOL))
    188                                                                         || (dlg.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL)) {
    189                                                                 dlg.panelMain.mark.setLightAtt(Att.COL, row, colour);
     186                                                if (((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, row)).contains("Al")) {
     187                                                        if (((colour == Col.UNKCOL) && (SmedAction.panelMain.mark.getLightAtt(Att.ALT, row) == Col.UNKCOL))
     188                                                                        || (SmedAction.panelMain.mark.getLightAtt(Att.COL, row) == Col.UNKCOL)) {
     189                                                                SmedAction.panelMain.mark.setLightAtt(Att.COL, row, colour);
    190190                                                        } else {
    191                                                                 dlg.panelMain.mark.setLightAtt(Att.ALT, row, colour);
     191                                                                SmedAction.panelMain.mark.setLightAtt(Att.ALT, row, colour);
    192192                                                        }
    193193                                                } else {
    194                                                         dlg.panelMain.mark.setLightAtt(Att.COL, row, colour);
     194                                                        SmedAction.panelMain.mark.setLightAtt(Att.COL, row, colour);
    195195                                                }
    196196                                }
     
    200200                        case 10:
    201201                        case 11:
    202                                 dlg.panelMain.mark.setLightAtt(col - 1, row, value);
     202                                SmedAction.panelMain.mark.setLightAtt(col - 1, row, value);
    203203                                break;
    204204                        case 6:
    205205                                if ((Boolean) value == true) {
    206                                         dlg.panelMain.mark.setLightAtt(Att.LIT, row, Lit.DIR);
    207                                         dlg.panelMain.mark.setLightAtt(Att.BEG, row, "");
    208                                         dlg.panelMain.mark.setLightAtt(Att.END, row, "");
     206                                        SmedAction.panelMain.mark.setLightAtt(Att.LIT, row, Lit.DIR);
     207                                        SmedAction.panelMain.mark.setLightAtt(Att.BEG, row, "");
     208                                        SmedAction.panelMain.mark.setLightAtt(Att.END, row, "");
    209209                                } else {
    210                                         dlg.panelMain.mark.setLightAtt(Att.LIT, row, Lit.UNKLIT);
    211                                         dlg.panelMain.mark.setLightAtt(Att.ORT, row, "");
     210                                        SmedAction.panelMain.mark.setLightAtt(Att.LIT, row, Lit.UNKLIT);
     211                                        SmedAction.panelMain.mark.setLightAtt(Att.ORT, row, "");
    212212                                }
    213213                                break;
    214214                        case 7:
    215215                        case 8:
    216                                 if (dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR) {
    217                                         dlg.panelMain.mark.setLightAtt(Att.ORT, row, value);
     216                                if (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR) {
     217                                        SmedAction.panelMain.mark.setLightAtt(Att.ORT, row, value);
    218218                                } else {
    219                                         dlg.panelMain.mark.setLightAtt(col - 1, row, value);
     219                                        SmedAction.panelMain.mark.setLightAtt(col - 1, row, value);
    220220                                }
    221221                                break;
     
    224224                                        String str = visibilities.get(vis);
    225225                                        if (str.equals(value))
    226                                                 dlg.panelMain.mark.setLightAtt(Att.VIS, row, vis);
     226                                                SmedAction.panelMain.mark.setLightAtt(Att.VIS, row, vis);
    227227                                }
    228228                                break;
     
    231231                                        String str = exhibitions.get(exh);
    232232                                        if (str.equals(value))
    233                                                 dlg.panelMain.mark.setLightAtt(Att.EXH, row, exh);
     233                                                SmedAction.panelMain.mark.setLightAtt(Att.EXH, row, exh);
    234234                                }
    235235                                break;
    236236                        default:
    237                                 dlg.panelMain.mark.setLightAtt(col - 1, row, value);
     237                                SmedAction.panelMain.mark.setLightAtt(col - 1, row, value);
    238238                        }
    239239                }
     
    261261                }
    262262                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
    263                         if (!((String)dlg.panelMain.mark.getLightAtt(Att.CHR, rowIndex)).contains("Al")) {
    264                                 col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
     263                        if (!((String)SmedAction.panelMain.mark.getLightAtt(Att.CHR, rowIndex)).contains("Al")) {
     264                                col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
    265265                        } else {
    266                                 col2Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.ALT, rowIndex)));
    267                         }
    268                         col1Label.setBackground(SeaMark.ColMAP.get(dlg.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
     266                                col2Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.ALT, rowIndex)));
     267                        }
     268                        col1Label.setBackground(SeaMark.ColMAP.get(SmedAction.panelMain.mark.getLightAtt(Att.COL, rowIndex)));
    269269                        return this;
    270270                }
     
    276276
    277277        public void addSector(int idx) {
    278                 dlg.panelMain.mark.addLight(idx);
     278                SmedAction.panelMain.mark.addLight(idx);
    279279                table.setSize(860, ((table.getRowCount() * 16) + 28));
    280280                if (table.getRowCount() > 3) {
     
    287287        public void deleteSector(int idx) {
    288288                if (idx > 0) {
    289                         dlg.panelMain.mark.delLight(idx);
     289                        SmedAction.panelMain.mark.delLight(idx);
    290290                        table.setSize(860, ((table.getRowCount() * 16) + 28));
    291291                        if (table.getRowCount() > 3) {
  • applications/editors/josm/plugins/smed/src/panels/PanelSpec.java

    r30737 r30738  
    2424                                int idx = categories.get(cat);
    2525                                if (dlg.node != null && (idx == categoryBox.getSelectedIndex()))
    26                                         dlg.panelMain.mark.setCategory(cat);
     26                                        SmedAction.panelMain.mark.setCategory(cat);
    2727                        }
    2828                }
     
    3535                                int idx = moorings.get(cat);
    3636                                if (dlg.node != null && (idx == mooringBox.getSelectedIndex())) {
    37                                         dlg.panelMain.mark.setCategory(cat);
     37                                        SmedAction.panelMain.mark.setCategory(cat);
    3838                                        if ((cat == Cat.INB_CALM) || (cat == Cat.INB_SBM)) {
    39                                                 dlg.panelMain.mark.setObject(Obj.BOYINB);
    40                                                 dlg.panelMain.mark.setShape(Shp.UNKSHP);
     39                                                SmedAction.panelMain.mark.setObject(Obj.BOYINB);
     40                                                SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    4141                                        } else {
    42                                                 dlg.panelMain.mark.setObject(Obj.MORFAC);
     42                                                SmedAction.panelMain.mark.setObject(Obj.MORFAC);
    4343                                                if (cat != Cat.MOR_BUOY)
    44                                                         dlg.panelMain.mark.setShape(Shp.UNKSHP);
     44                                                        SmedAction.panelMain.mark.setShape(Shp.UNKSHP);
    4545                                        }
    4646                                }
     
    6666        public ActionListener alShape = new ActionListener() {
    6767                public void actionPerformed(java.awt.event.ActionEvent e) {
    68                         if ((dlg.panelMain.mark.getObject() != Obj.MORFAC) || (dlg.panelMain.mark.getCategory() == Cat.MOR_BUOY)) {
     68                        if ((SmedAction.panelMain.mark.getObject() != Obj.MORFAC) || (SmedAction.panelMain.mark.getCategory() == Cat.MOR_BUOY)) {
    6969                                for (Shp shp : shapes.keySet()) {
    7070                                        JRadioButton button = shapes.get(shp);
    7171                                        if (button.isSelected()) {
    72                                                 dlg.panelMain.mark.setShape(shp);
    73                                                 if (SeaMark.EntMAP.get(dlg.panelMain.mark.getObject()) != Ent.MOORING) {
    74                                                         dlg.panelMain.mark.setObject(objects.get(shp));
    75                                                         if (dlg.panelMain.mark.getObjColour(0) == Col.UNKCOL) {
    76                                                                 dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
    77                                                                 dlg.panelMain.mark.setObjColour(Col.YELLOW);
     72                                                SmedAction.panelMain.mark.setShape(shp);
     73                                                if (SeaMark.EntMAP.get(SmedAction.panelMain.mark.getObject()) != Ent.MOORING) {
     74                                                        SmedAction.panelMain.mark.setObject(objects.get(shp));
     75                                                        if (SmedAction.panelMain.mark.getObjColour(0) == Col.UNKCOL) {
     76                                                                SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
     77                                                                SmedAction.panelMain.mark.setObjColour(Col.YELLOW);
    7878                                                        }
    7979                                                        if (button == cairnButton) {
    80                                                                 dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
    81                                                                 dlg.panelMain.mark.setObjColour(Col.UNKCOL);
     80                                                                SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
     81                                                                SmedAction.panelMain.mark.setObjColour(Col.UNKCOL);
    8282                                                        }
    83                                                         topmarkButton.setVisible(dlg.panelMain.mark.testValid());
     83                                                        topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
    8484                                                }
    8585                                                button.setBorderPainted(true);
     
    8787                                                button.setBorderPainted(false);
    8888                                }
    89                                 dlg.panelMain.panelMore.syncPanel();
     89                                SmedAction.panelMain.panelMore.syncPanel();
    9090                        }
    9191                }
     
    9595                public void actionPerformed(java.awt.event.ActionEvent e) {
    9696                        if (topmarkButton.isSelected()) {
    97                                 dlg.panelMain.mark.setTopmark(Top.X_SHAPE);
    98                                 dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
    99                                 dlg.panelMain.mark.setTopColour(Col.YELLOW);
     97                                SmedAction.panelMain.mark.setTopmark(Top.X_SHAPE);
     98                                SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
     99                                SmedAction.panelMain.mark.setTopColour(Col.YELLOW);
    100100                                topmarkButton.setBorderPainted(true);
    101101                        } else {
    102                                 dlg.panelMain.mark.setTopmark(Top.NOTOP);
    103                                 dlg.panelMain.mark.setTopPattern(Pat.NOPAT);
    104                                 dlg.panelMain.mark.setTopColour(Col.UNKCOL);
     102                                SmedAction.panelMain.mark.setTopmark(Top.NOTOP);
     103                                SmedAction.panelMain.mark.setTopPattern(Pat.NOPAT);
     104                                SmedAction.panelMain.mark.setTopColour(Col.UNKCOL);
    105105                                topmarkButton.setBorderPainted(false);
    106106                        }
    107                         dlg.panelMain.panelTop.syncPanel();
     107                        SmedAction.panelMain.panelTop.syncPanel();
    108108                }
    109109        };
     
    111111        private ActionListener alNotice = new ActionListener() {
    112112                public void actionPerformed(java.awt.event.ActionEvent e) {
    113                         dlg.panelMain.mark.clrMark();
     113                        SmedAction.panelMain.mark.clrMark();
    114114                        if (noticeButton.isSelected()) {
    115                                 dlg.panelMain.mark.setObject(Obj.NOTMRK);
     115                                SmedAction.panelMain.mark.setObject(Obj.NOTMRK);
    116116                                noticeButton.setBorderPainted(true);
    117117                        } else {
    118                                 dlg.panelMain.mark.setObject(Obj.UNKOBJ);
     118                                SmedAction.panelMain.mark.setObject(Obj.UNKOBJ);
    119119                                noticeButton.setBorderPainted(false);
    120120                        }
    121                         dlg.panelMain.syncPanel();
     121                        SmedAction.panelMain.syncPanel();
    122122                }
    123123        };
     
    125125        private ActionListener alMooring = new ActionListener() {
    126126                public void actionPerformed(java.awt.event.ActionEvent e) {
    127                         dlg.panelMain.mark.setObject(Obj.UNKOBJ);
    128                         dlg.panelMain.mark.setCategory(Cat.NOCAT);
    129                         dlg.panelMain.mark.setTopmark(Top.NOTOP);
     127                        SmedAction.panelMain.mark.setObject(Obj.UNKOBJ);
     128                        SmedAction.panelMain.mark.setCategory(Cat.NOCAT);
     129                        SmedAction.panelMain.mark.setTopmark(Top.NOTOP);
    130130                        if (mooringButton.isSelected()) {
    131                                 dlg.panelMain.mark.setObject(Obj.MORFAC);
     131                                SmedAction.panelMain.mark.setObject(Obj.MORFAC);
    132132                                categoryBox.setVisible(false);
    133133                                mooringBox.setVisible(true);
     
    234234
    235235        public void syncPanel() {
    236                 if (SeaMark.EntMAP.get(dlg.panelMain.mark.getObject()) == Ent.MOORING) {
     236                if (SeaMark.EntMAP.get(SmedAction.panelMain.mark.getObject()) == Ent.MOORING) {
    237237                        mooringButton.setBorderPainted(true);
    238238                        categoryBox.setVisible(false);
     
    248248                        for (Cat cat : moorings.keySet()) {
    249249                                int item = moorings.get(cat);
    250                                 if (dlg.panelMain.mark.getCategory() == cat)
     250                                if (SmedAction.panelMain.mark.getCategory() == cat)
    251251                                        mooringBox.setSelectedIndex(item);
    252252                        }
     
    262262                        cairnButton.setEnabled(true);
    263263                        noticeButton.setEnabled(true);
    264                         topmarkButton.setBorderPainted(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
    265                         topmarkButton.setSelected(dlg.panelMain.mark.getTopmark() != Top.NOTOP);
    266                         topmarkButton.setVisible(dlg.panelMain.mark.testValid());
     264                        topmarkButton.setBorderPainted(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
     265                        topmarkButton.setSelected(SmedAction.panelMain.mark.getTopmark() != Top.NOTOP);
     266                        topmarkButton.setVisible(SmedAction.panelMain.mark.testValid());
    267267                        for (Cat cat : categories.keySet()) {
    268268                                int item = categories.get(cat);
    269                                 if (dlg.panelMain.mark.getCategory() == cat)
     269                                if (SmedAction.panelMain.mark.getCategory() == cat)
    270270                                        categoryBox.setSelectedIndex(item);
    271271                        }
     
    273273                for (Shp shp : shapes.keySet()) {
    274274                        JRadioButton button = shapes.get(shp);
    275                         if (dlg.panelMain.mark.getShape() == shp) {
     275                        if (SmedAction.panelMain.mark.getShape() == shp) {
    276276                                button.setBorderPainted(true);
    277277                        } else
     
    279279                }
    280280                noticeButton.setBorderPainted(false);
    281                 dlg.panelMain.mark.testValid();
     281                SmedAction.panelMain.mark.testValid();
    282282        }
    283283
  • applications/editors/josm/plugins/smed/src/panels/PanelStbd.java

    r30737 r30738  
    3131                                JRadioButton button = shapes.get(shp);
    3232                                if (button.isSelected()) {
    33                                         dlg.panelMain.mark.setShape(shp);
    34                                         dlg.panelMain.mark.setObject(objects.get(shp));
     33                                        SmedAction.panelMain.mark.setShape(shp);
     34                                        SmedAction.panelMain.mark.setObject(objects.get(shp));
    3535                                        button.setBorderPainted(true);
    3636                                } else
    3737                                        button.setBorderPainted(false);
    3838                        }
    39                         if (dlg.panelMain.mark.testValid()) {
    40                                 dlg.panelMain.panelChan.topmarkButton.setVisible(true);
    41                                 dlg.panelMain.panelChan.lightButton.setVisible(true);
    42                                 if (dlg.panelMain.mark.getCategory() == Cat.LAM_STBD) {
    43                                         switch (dlg.panelMain.mark.getRegion()) {
     39                        if (SmedAction.panelMain.mark.testValid()) {
     40                                SmedAction.panelMain.panelChan.topmarkButton.setVisible(true);
     41                                SmedAction.panelMain.panelChan.lightButton.setVisible(true);
     42                                if (SmedAction.panelMain.mark.getCategory() == Cat.LAM_STBD) {
     43                                        switch (SmedAction.panelMain.mark.getRegion()) {
    4444                                        case A:
    45                                                 dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
    46                                                 dlg.panelMain.mark.setObjColour(Col.GREEN);
     45                                                SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
     46                                                SmedAction.panelMain.mark.setObjColour(Col.GREEN);
    4747                                                break;
    4848                                        case B:
    49                                                 dlg.panelMain.mark.setObjPattern(Pat.NOPAT);
    50                                                 dlg.panelMain.mark.setObjColour(Col.RED);
     49                                                SmedAction.panelMain.mark.setObjPattern(Pat.NOPAT);
     50                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
    5151                                                break;
    5252                                        case C:
    53                                                 dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
    54                                                 dlg.panelMain.mark.setObjColour(Col.GREEN);
    55                                                 dlg.panelMain.mark.addObjColour(Col.WHITE);
    56                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
    57                                                 dlg.panelMain.mark.addObjColour(Col.WHITE);
     53                                                SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
     54                                                SmedAction.panelMain.mark.setObjColour(Col.GREEN);
     55                                                SmedAction.panelMain.mark.addObjColour(Col.WHITE);
     56                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
     57                                                SmedAction.panelMain.mark.addObjColour(Col.WHITE);
    5858                                                break;
    5959                                        }
    6060                                } else {
    61                                         dlg.panelMain.mark.setObjPattern(Pat.HSTRP);
    62                                         switch (dlg.panelMain.mark.getRegion()) {
     61                                        SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP);
     62                                        switch (SmedAction.panelMain.mark.getRegion()) {
    6363                                        case A:
    64                                                 dlg.panelMain.mark.setObjColour(Col.GREEN);
    65                                                 dlg.panelMain.mark.addObjColour(Col.RED);
    66                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
     64                                                SmedAction.panelMain.mark.setObjColour(Col.GREEN);
     65                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
     66                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
    6767                                                break;
    6868                                        case B:
    69                                                 dlg.panelMain.mark.setObjColour(Col.RED);
    70                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
    71                                                 dlg.panelMain.mark.addObjColour(Col.RED);
     69                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
     70                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
     71                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
    7272                                                break;
    7373                                        case C:
    74                                                 dlg.panelMain.mark.setObjColour(Col.RED);
    75                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
    76                                                 dlg.panelMain.mark.addObjColour(Col.RED);
    77                                                 dlg.panelMain.mark.addObjColour(Col.GREEN);
     74                                                SmedAction.panelMain.mark.setObjColour(Col.RED);
     75                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
     76                                                SmedAction.panelMain.mark.addObjColour(Col.RED);
     77                                                SmedAction.panelMain.mark.addObjColour(Col.GREEN);
    7878                                                break;
    7979                                        }
    8080                                }
    81                                 dlg.panelMain.panelMore.syncPanel();
     81                                SmedAction.panelMain.panelMore.syncPanel();
    8282                        } else {
    83                                 dlg.panelMain.panelChan.topmarkButton.setVisible(false);
    84                                 dlg.panelMain.panelChan.lightButton.setVisible(false);
     83                                SmedAction.panelMain.panelChan.topmarkButton.setVisible(false);
     84                                SmedAction.panelMain.panelChan.lightButton.setVisible(false);
    8585                        }
    8686                }
     
    104104                for (Shp shp : shapes.keySet()) {
    105105                        JRadioButton button = shapes.get(shp);
    106                         if (dlg.panelMain.mark.getShape() == shp) {
     106                        if (SmedAction.panelMain.mark.getShape() == shp) {
    107107                                button.setBorderPainted(true);
    108108                        } else
  • applications/editors/josm/plugins/smed/src/panels/PanelTop.java

    r30737 r30738  
    3838                                JRadioButton button = tops.get(top);
    3939                                if (button.isSelected()) {
    40                                         dlg.panelMain.mark.setTopmark(top);
     40                                        SmedAction.panelMain.mark.setTopmark(top);
    4141                                        button.setBorderPainted(true);
    4242                                } else
     
    7979                for (Top top : tops.keySet()) {
    8080                        JRadioButton button = tops.get(top);
    81                         if (dlg.panelMain.mark.getTopmark() == top) {
     81                        if (SmedAction.panelMain.mark.getTopmark() == top) {
    8282                                button.setBorderPainted(true);
    8383                        } else
  • applications/editors/josm/plugins/smed/src/seamarks/SeaMark.java

    r30737 r30738  
    13611361                }
    13621362                if (tmp) {
    1363                         dlg.panelMain.moreButton.setVisible(true);
    1364                         dlg.panelMain.saveButton.setEnabled(true);
    1365                         dlg.panelMain.topButton.setEnabled(true);
    1366                         dlg.panelMain.fogButton.setEnabled(true);
    1367                         dlg.panelMain.radButton.setEnabled(true);
    1368                         dlg.panelMain.litButton.setEnabled(true);
     1363                        SmedAction.panelMain.moreButton.setVisible(true);
     1364                        SmedAction.panelMain.saveButton.setEnabled(true);
     1365                        SmedAction.panelMain.topButton.setEnabled(true);
     1366                        SmedAction.panelMain.fogButton.setEnabled(true);
     1367                        SmedAction.panelMain.radButton.setEnabled(true);
     1368                        SmedAction.panelMain.litButton.setEnabled(true);
    13691369                        return true;
    13701370                } else {
    1371                         dlg.panelMain.moreButton.setVisible(false);
    1372                         dlg.panelMain.moreButton.setText(">>");
    1373                         dlg.panelMain.topButton.setEnabled(false);
    1374                         dlg.panelMain.fogButton.setEnabled(false);
    1375                         dlg.panelMain.radButton.setEnabled(false);
    1376                         dlg.panelMain.litButton.setEnabled(false);
     1371                        SmedAction.panelMain.moreButton.setVisible(false);
     1372                        SmedAction.panelMain.moreButton.setText(">>");
     1373                        SmedAction.panelMain.topButton.setEnabled(false);
     1374                        SmedAction.panelMain.fogButton.setEnabled(false);
     1375                        SmedAction.panelMain.radButton.setEnabled(false);
     1376                        SmedAction.panelMain.litButton.setEnabled(false);
    13771377                        PanelMain.messageBar.setText("Seamark not recognised");
    13781378                        return false;
     
    13981398                setSource("");
    13991399                setFixme("");
    1400                 dlg.panelMain.syncPanel();
     1400                SmedAction.panelMain.syncPanel();
    14011401                repaint();
    14021402        }
  • applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveGpsLayerTimerTask.java

    r30646 r30738  
    6868            // @see LiveGpsLayer
    6969            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(tmpFile)));
    70             GpxWriter gpxWriter = new GpxWriter(out);
    71             gpxWriter.write(gpsLayer.data);
    72             gpxWriter.close();
     70            try (GpxWriter gpxWriter = new GpxWriter(out)) {
     71                gpxWriter.write(gpsLayer.data);
     72            }
    7373            tmpFile.renameTo(file);
    7474        } catch (IOException ioExc) {
  • applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorShowAction.java

    r30737 r30738  
    2626
    2727import org.openstreetmap.josm.Main;
     28import org.openstreetmap.josm.actions.JosmAction;
    2829import org.openstreetmap.josm.tools.Shortcut;
    2930import org.openstreetmap.josm.tools.XmlObjectParser;
    30 import org.openstreetmap.josm.actions.JosmAction;
    3131import org.xml.sax.SAXException;
    3232
     
    5050    }
    5151
    52     public void actionPerformed(ActionEvent e) {
     52    @Override
     53        public void actionPerformed(ActionEvent e) {
    5354        if(surveyorFrame == null) {
    5455            surveyorFrame = new JFrame();
     
    6465            // zoomout:
    6566            actionMap.put("zoomout", new AbstractAction() {
    66                 public void actionPerformed(ActionEvent e) {
     67                @Override
     68                                public void actionPerformed(ActionEvent e) {
    6769                    if(Main.map != null && Main.map.mapView != null) {
    6870                        Main.map.mapView.zoomToFactor(2);
     
    7375            // zoomin:
    7476            actionMap.put("zoomin", new AbstractAction() {
    75                 public void actionPerformed(ActionEvent e) {
     77                @Override
     78                                public void actionPerformed(ActionEvent e) {
    7679                    if(Main.map != null && Main.map.mapView != null) {
    7780                        Main.map.mapView.zoomToFactor(1/2);
     
    8285            // autocenter:
    8386            actionMap.put("autocenter", new AbstractAction() {
    84                 public void actionPerformed(ActionEvent e) {
     87                @Override
     88                                public void actionPerformed(ActionEvent e) {
    8589                    // toggle autocenter
    8690                    gpsPlugin.setAutoCenter(!gpsPlugin.isAutoCenter());
     
    105109
    106110    public SurveyorComponent createComponent() {
    107         InputStream in = null;
    108111        String source = Main.pref.get("surveyor.source");
    109112        if(source == null || source.length() == 0) {
     
    114117            // </FIXXME>
    115118        }
    116         SurveyorComponent component= null;
    117         try {
    118             in = ResourceLoader.getInputStream(source);
    119             component = createComponent(in);
    120             in.close();
    121             return component;
     119        try (InputStream in = ResourceLoader.getInputStream(source)) {
     120            return createComponent(in);
    122121        } catch (IOException e) {
    123             e.printStackTrace();
     122            Main.error(e);
    124123            JOptionPane.showMessageDialog(Main.parent, tr("Could not read surveyor definition: {0}",source));
    125124        } catch (SAXException e) {
    126             e.printStackTrace();
     125            Main.error(e);
    127126            JOptionPane.showMessageDialog(Main.parent, tr("Error parsing {0}: {1}", source, e.getMessage()));
    128127        }
    129         return component;
     128        return null;
    130129    }
    131130
  • applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/ResourceLoader.java

    r30646 r30738  
    2828     * @throws IOException if an error occurs on opening the url, or if the file is not found.
    2929     */
    30     public static InputStream getInputStream(String source) throws IOException {
     30    @SuppressWarnings("resource")
     31        public static InputStream getInputStream(String source) throws IOException {
    3132        InputStream in = null;
    3233        if (source.startsWith("http://") || source.startsWith("https://") || source.startsWith("ftp://") || source.startsWith("file:")) {
  • applications/editors/josm/plugins/tageditor/src/org/openstreetmap/josm/plugins/tageditor/tagspec/TagSpecifications.java

    r30737 r30738  
    2626/**
    2727 * This class manages a list of {@link TagSpecification}s.
    28  * 
     28 *
    2929 * It also provides a method for reading a list of {@link TagSpecification}s from
    3030 * an XML file.
    31  * 
     31 *
    3232 * @author Gubaer
    3333 *
     
    6363     * loads the tag specifications from the resource file given by
    6464     * {@link #RES_NAME_TAG_SPECIFICATIONS}.
    65      * 
     65     *
    6666     * @return the list of {@link TagSpecification}s
    6767     * @throws Exception thrown, if an exception occurs
     
    7171        if (in == null) {
    7272            logger.log(Level.SEVERE, "failed to create input stream for resource '" + RES_NAME_TAG_SPECIFICATIONS + "'");
    73         }
    74         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    75         TagSpecifications spec = new TagSpecifications();
    76         spec.load(reader);
    77         reader.close();
    78         instance = spec;
    79 
     73            return;
     74        }
     75        try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
     76                TagSpecifications spec = new TagSpecifications();
     77                spec.load(reader);
     78                instance = spec;
     79        }
    8080    }
    8181
     
    9797    /**
    9898     * loads the tag specifications from a specific reader
    99      * 
     99     *
    100100     * @param in  the reader to read from
    101101     * @throws Exception thrown, if an exception occurs
     
    156156        return items;
    157157    }
    158    
     158
    159159    /**
    160160     * replies a list of {@see KeyValuePair}s for all {@see TagSpecification}s and
    161161     * {@see LableSpecification}s.
    162      * 
     162     *
    163163     * @return the list
    164164     */
     
    178178    /**
    179179     * The SAX handler for reading XML files with tag specifications
    180      * 
     180     *
    181181     * @author gubaer
    182182     *
     
    212212         * parses a string value consisting of 'yes' or 'no' (exactly, case
    213213         * sensitive)
    214          * 
     214         *
    215215         * @param value the string value
    216216         * @return true, if value is <code>yes</code>; false, if value is <code>no</code>
     
    228228        /**
    229229         * handles a start element with name <code>osm-tag-definitions</code>
    230          * 
     230         *
    231231         * @param atts  the XML attributes
    232232         * @throws SAXException
     
    238238        /**
    239239         * handles an end element with name <code>osm-tag-specifications</code>
    240          * 
     240         *
    241241         * @throws SAXException
    242242         */
     
    247247        /**
    248248         * handles a start element with name <code>tag</code>
    249          * 
     249         *
    250250         * @param atts the XML attributes of the element
    251251         * @throws SAXException
     
    285285        /**
    286286         * handles a start element with name <code>label</code>
    287          * 
     287         *
    288288         * @param atts the XML attributes
    289289         * @throws SAXException
     
    311311        /**
    312312         * handles an end element with name <code>label</code>
    313          * 
     313         *
    314314         * @throws SAXException
    315315         */
     
    352352    class ResourceEntityResolver implements EntityResolver {
    353353
    354         public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
     354        @Override
     355                public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    355356            if (systemId != null && systemId.endsWith(DTD)) {
    356357                InputStream stream = TagSpecifications.class.getResourceAsStream("/resources/"+DTD);
  • applications/editors/josm/plugins/tracer2/src/org/openstreetmap/josm/plugins/tracer2/preferences/ServerParamList.java

    r30737 r30738  
    11/**
    22 *  Tracer2 - plug-in for JOSM to capture contours
    3  * 
     3 *
    44 *  This program is free software; you can redistribute it and/or modify
    55 *  it under the terms of the GNU General Public License as published by
    66 *  the Free Software Foundation; either version 2 of the License, or
    77 *  (at your option) any later version.
    8  * 
     8 *
    99 *  This program is distributed in the hope that it will be useful,
    1010 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    1111 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1212 *  GNU General Public License for more details.
    13  * 
     13 *
    1414 *  You should have received a copy of the GNU General Public License along
    1515 *  with this program; if not, write to the Free Software Foundation, Inc.,
     
    2828import java.util.List;
    2929
     30import org.openstreetmap.josm.Main;
     31
    3032public class ServerParamList {
    3133    ArrayList<ServerParam> m_listServerParam = new ArrayList<>();
    3234    ServerParam m_oActivParam = null;
    3335    String m_strFilename;
    34    
     36
    3537    public ServerParamList(String filename) {
    3638        this.m_strFilename = filename;
     
    4143        }
    4244    }
    43    
     45
    4446    public void load() {
    45         try {
    46             BufferedReader oReader = new BufferedReader(new InputStreamReader(new FileInputStream(m_strFilename), "UTF-8"));
     47        try (BufferedReader oReader = new BufferedReader(new InputStreamReader(new FileInputStream(m_strFilename), "UTF-8"))) {
    4748            StringBuilder oBuilder = new StringBuilder();
    4849            String strLine;
     
    5455                }
    5556            }
    56             oReader.close();
    5757        } catch (Exception e) {
    5858                loadDefault();
    5959        }
    6060    }
    61    
     61
    6262    public void loadDefault() {
    63         try {
     63        try (
    6464                InputStream oIP = getClass().getResourceAsStream("/resources/serverParam.cfg");
    6565            BufferedReader oReader = new BufferedReader(new InputStreamReader(oIP));
     66        ) {
    6667            StringBuilder oBuilder = new StringBuilder();
    6768            String strLine;
     
    7374                }
    7475            }
    75             oReader.close();
    7676        } catch (Exception e) {
    77                 System.err.println("Tracer2 warning: can't load file " + m_strFilename);
    78             //e.printStackTrace();
     77                Main.warn("Tracer2 warning: can't load file " + m_strFilename);
    7978        }
    8079    }
    8180
    8281    public void save() {
    83         try {
    84             OutputStreamWriter oWriter = new OutputStreamWriter(new FileOutputStream(m_strFilename), "UTF-8");
     82        try (OutputStreamWriter oWriter = new OutputStreamWriter(new FileOutputStream(m_strFilename), "UTF-8")) {
    8583            for (ServerParam param : m_listServerParam) {
    8684                oWriter.write(param.serialize());
    8785            }
    88             oWriter.close();
    8986        } catch (Exception e) {
    90                 System.err.println("Tracer2 warning: can't save file " + m_strFilename);
    91             //e.printStackTrace();
     87                Main.warn("Tracer2 warning: can't save file " + m_strFilename);
    9288        }
    9389    }
    94    
     90
    9591    public List<ServerParam> getParamList() {
    9692        return m_listServerParam;
    9793    }
    98    
     94
    9995    public ServerParam getActivParam() {
    10096        return m_oActivParam;
     
    105101        }
    106102    }
    107    
     103
    108104    public List<ServerParam> getEnableParamList() {
    109105        List<ServerParam> listParam = new ArrayList<>();
     
    115111        return listParam;
    116112    }
    117    
     113
    118114    public void addParam(ServerParam param) {
    119115        m_listServerParam.add(param);
    120116    }
    121    
     117
    122118    public void removeParam(ServerParam param) {
    123119        param.setEnabled(false);
    124120        m_listServerParam.remove(param);
    125121    }
    126    
    127122}
  • applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java

    r30724 r30738  
    1313import org.bouncycastle.bcpg.BCPGOutputStream;
    1414import org.bouncycastle.openpgp.PGPSignature;
     15import org.openstreetmap.josm.Main;
    1516
    1617public class TrustSignatures {
     
    126127        if (textsigs.containsKey(plain)){
    127128            List<PGPSignature> l = textsigs.get(plain);
    128             try {
    129                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
    130                 ArmoredOutputStream aOut = new ArmoredOutputStream(baos);
     129            ByteArrayOutputStream baos = new ByteArrayOutputStream();
     130            try (ArmoredOutputStream aOut = new ArmoredOutputStream(baos)) {
    131131                aOut.beginClearText(l.get(0).getHashAlgorithm());
    132132                aOut.write(plain.getBytes(Charset.forName("UTF-8")));
     
    134134                aOut.endClearText();
    135135
    136                 BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    137                 for (PGPSignature sig : l) {
    138                     sig.encode(bOut);
     136                try (BCPGOutputStream bOut = new BCPGOutputStream(aOut)) {
     137                            for (PGPSignature sig : l) {
     138                                sig.encode(bOut);
     139                            }
    139140                }
    140 
    141                 bOut.close();
    142                 aOut.close();
    143141
    144142                return baos.toString("UTF-8");
    145143
    146144            } catch (Exception e) {
    147                 e.printStackTrace();
     145                Main.error(e);
    148146                return "Error - read console Output";
    149147            }
     
    153151
    154152    public String getArmoredFulltextSignature(PGPSignature sig) {
    155         try {
    156             ByteArrayOutputStream baos = new ByteArrayOutputStream();
    157             ArmoredOutputStream aOut = new ArmoredOutputStream(baos);
     153        ByteArrayOutputStream baos = new ByteArrayOutputStream();
     154        try (ArmoredOutputStream aOut = new ArmoredOutputStream(baos)) {
    158155            aOut.beginClearText(sig.getHashAlgorithm());
    159156            aOut.write(getSigtext(sig).getBytes(Charset.forName("UTF-8")));
     
    161158            aOut.endClearText();
    162159
    163             BCPGOutputStream bOut = new BCPGOutputStream(aOut);
    164             sig.encode(bOut);
    165             bOut.close();
    166             aOut.close();
    167 
     160            try (BCPGOutputStream bOut = new BCPGOutputStream(aOut)) {
     161                sig.encode(bOut);
     162            }
    168163
    169164            return baos.toString("UTF-8");
    170165        } catch (Exception e) {
    171             e.printStackTrace();
     166            Main.error(e);
    172167            return "Error - read console Output";
    173168        }
    174169    }
    175 
    176170}
  • applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java

    r30724 r30738  
    88/**
    99 * This class is released under GNU general public license
    10  * 
     10 *
    1111 * Description: This class generates random names from syllables, and provides programmer a
    1212 * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names.
    13  * 
     13 *
    1414 * SYLLABLE FILE REQUIREMENTS/FORMAT:
    1515 * 1) all syllables are separated by line break.
     
    1717 * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results.
    1818 * 4) Empty lines are ignored.
    19  * 
     19 *
    2020 * SYLLABLE CLASSIFICATION:
    2121 * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix.
     
    2323 * To declare syllable as a suffix in the file, insert "+" as a first character of the line.
    2424 * everything else is read as a middle part.
    25  * 
     25 *
    2626 * NUMBER OF SYLLABLES:
    2727 * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix.
    2828 * In case of 1 syllable, name will be chosen from amongst the prefixes.
    2929 * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix.
    30  * 
     30 *
    3131 * ASSIGNING RULES:
    3232 * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the
    3333 * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important.
    34  * 
     34 *
    3535 * RULES:
    3636 * 1) +v means that next syllable must definitely start with a vocal.
     
    4141 * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only vocals, which will be detected
    4242 * and RuntimeException will be thrown.
    43  * 
     43 *
    4444 * TO START:
    4545 * Create a new NameGenerator object, provide the syllable file, and create names using compose() method.
    46  * 
     46 *
    4747 * @author Joonas Vali, August 2009.
    4848 *
     
    8585     */
    8686    public void refresh() throws IOException{
    87 
    88         FileReader input = null;
    89         BufferedReader bufRead;
    90         String line;
    91 
    92         input = new FileReader(fileName);
    93 
    94         bufRead = new BufferedReader(input);
    95         line="";
    96 
    97         while(line != null){
    98             line = bufRead.readLine();
    99             if(line != null && !line.equals("")){
    100                 if(line.charAt(0) == '-'){
    101                     pre.add(line.substring(1).toLowerCase());
    102                 }
    103                 else if(line.charAt(0) == '+'){
    104                     sur.add(line.substring(1).toLowerCase());
    105                 }
    106                 else{
    107                     mid.add(line.toLowerCase());
    108                 }
    109             }
    110         }
    111         bufRead.close();
    112     }
    113 
    114     private String upper(String s){
     87        try (
     88                FileReader input = new FileReader(fileName);
     89                BufferedReader bufRead = new BufferedReader(input);
     90                ) {
     91                String line="";
     92                while (line != null){
     93                    line = bufRead.readLine();
     94                    if (line != null && !line.equals("")) {
     95                        if(line.charAt(0) == '-') {
     96                            pre.add(line.substring(1).toLowerCase());
     97                        } else if (line.charAt(0) == '+') {
     98                            sur.add(line.substring(1).toLowerCase());
     99                        } else {
     100                            mid.add(line.toLowerCase());
     101                        }
     102                    }
     103                }
     104        }
     105    }
     106
     107    private String upper(String s) {
    115108        return s.substring(0,1).toUpperCase().concat(s.substring(1));
    116109    }
    117110
    118     private boolean containsConsFirst(ArrayList<String> array){
     111    private boolean containsConsFirst(ArrayList<String> array) {
    119112        for(String s: array){
    120113            if(consonantFirst(s)) return true;
  • applications/editors/josm/plugins/trustosm/src/tools/NameGenerator.java

    r30737 r30738  
    88/**
    99 * This class is released under GNU general public license
    10  * 
     10 *
    1111 * Description: This class generates random names from syllables, and provides programmer a
    1212 * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names.
    13  * 
     13 *
    1414 * SYLLABLE FILE REQUIREMENTS/FORMAT:
    1515 * 1) all syllables are separated by line break.
     
    1717 * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results.
    1818 * 4) Empty lines are ignored.
    19  * 
     19 *
    2020 * SYLLABLE CLASSIFICATION:
    2121 * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix.
     
    2323 * To declare syllable as a suffix in the file, insert "+" as a first character of the line.
    2424 * everything else is read as a middle part.
    25  * 
     25 *
    2626 * NUMBER OF SYLLABLES:
    2727 * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix.
    2828 * In case of 1 syllable, name will be chosen from amongst the prefixes.
    2929 * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix.
    30  * 
     30 *
    3131 * ASSIGNING RULES:
    3232 * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the
    3333 * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important.
    34  * 
     34 *
    3535 * RULES:
    3636 * 1) +v means that next syllable must definitely start with a vocal.
     
    4141 * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only vocals, which will be detected
    4242 * and RuntimeException will be thrown.
    43  * 
     43 *
    4444 * TO START:
    4545 * Create a new NameGenerator object, provide the syllable file, and create names using compose() method.
    46  * 
     46 *
    4747 * @author Joonas Vali, August 2009.
    4848 *
     
    8585     */
    8686    public void refresh() throws IOException{
    87 
    88         FileReader input = null;
    89         BufferedReader bufRead;
    90         String line;
    91 
    92         input = new FileReader(fileName);
    93 
    94         bufRead = new BufferedReader(input);
    95         line="";
    96 
    97         while(line != null){
    98             line = bufRead.readLine();
    99             if(line != null && !line.equals("")){
    100                 if(line.charAt(0) == '-'){
    101                     pre.add(line.substring(1).toLowerCase());
    102                 }
    103                 else if(line.charAt(0) == '+'){
    104                     sur.add(line.substring(1).toLowerCase());
    105                 }
    106                 else{
    107                     mid.add(line.toLowerCase());
    108                 }
    109             }
    110         }
    111         bufRead.close();
    112     }
    113 
    114     private String upper(String s){
     87        try (
     88                FileReader input = new FileReader(fileName);
     89                BufferedReader bufRead = new BufferedReader(input);
     90        ) {
     91                String line="";
     92
     93                while (line != null) {
     94                    line = bufRead.readLine();
     95                    if (line != null && !line.equals("")) {
     96                        if (line.charAt(0) == '-') {
     97                            pre.add(line.substring(1).toLowerCase());
     98                        } else if (line.charAt(0) == '+') {
     99                            sur.add(line.substring(1).toLowerCase());
     100                        } else{
     101                            mid.add(line.toLowerCase());
     102                        }
     103                    }
     104                }
     105        }
     106    }
     107
     108    private String upper(String s) {
    115109        return s.substring(0,1).toUpperCase().concat(s.substring(1));
    116110    }
    117111
    118     private boolean containsConsFirst(ArrayList<String> array){
    119         for(String s: array){
    120             if(consonantFirst(s)) return true;
     112    private boolean containsConsFirst(ArrayList<String> array) {
     113        for (String s: array) {
     114            if (consonantFirst(s)) return true;
    121115        }
    122116        return false;
  • applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersAddLayerAction.java

    r29854 r30738  
    2525    }
    2626
    27     public void actionPerformed(ActionEvent e) {
     27    @Override
     28        public void actionPerformed(ActionEvent e) {
    2829        String wpid = JOptionPane.showInputDialog(Main.parent,
    2930            tr("Enter a walking-papers.org URL or ID (the bit after the ?id= in the URL)"),
     
    5152        String tile = null;
    5253
    53         try {
    54             BufferedReader r = new BufferedReader(new InputStreamReader(new URL(wpUrl).openStream(), "utf-8"));
     54        try (BufferedReader r = new BufferedReader(new InputStreamReader(new URL(wpUrl).openStream(), "utf-8"))) {
    5555            for (String line = r.readLine(); line != null; line = r.readLine()) {
    5656                m = spanPattern.matcher(line);
     
    6565                }
    6666            }
    67             r.close();
    68             if ((tile == null) || (north == 0 && south == 0) || (east == 0 && west == 0)) throw new Exception();
     67            if ((tile == null) || (north == 0 && south == 0) || (east == 0 && west == 0)) {
     68                throw new IllegalStateException();
     69            }
    6970        } catch (Exception ex) {
    7071            JOptionPane.showMessageDialog(Main.parent,tr("Could not read information from walking-papers.org the id \"{0}\"", mungedWpId));
  • applications/editors/josm/plugins/wikipedia/src/org/wikipedia/WikipediaApp.java

    r30737 r30738  
    2525import javax.xml.xpath.XPathFactory;
    2626
     27import org.openstreetmap.josm.Main;
    2728import org.openstreetmap.josm.data.coor.LatLon;
    2829import org.openstreetmap.josm.data.osm.OsmPrimitive;
     
    116117                connection.setDoOutput(true);
    117118
    118                 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
    119                 out.write("articles=" + encodeURL(Utils.join(",", articleNames)));
    120                 out.close();
    121 
     119                try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
     120                        out.write("articles=" + encodeURL(Utils.join(",", articleNames)));
     121                }
    122122
    123123                final Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\n");
     
    129129                        status.put(x[0], "1".equals(x[1]));
    130130                    } else {
    131                         System.err.println("Unknown element " + line);
     131                        Main.error("Unknown element " + line);
    132132                    }
    133133                }
Note: See TracChangeset for help on using the changeset viewer.