Ignore:
Timestamp:
2016-06-01T00:55:28+02:00 (8 years ago)
Author:
donvip
Message:

sonar - fix many issues

Location:
applications/editors/josm/plugins/cadastre-fr
Files:
1 added
11 edited

Legend:

Unmodified
Added
Removed
  • applications/editors/josm/plugins/cadastre-fr/.settings/org.eclipse.jdt.core.prefs

    r30736 r32211  
    112112org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
    113113org.eclipse.jdt.core.compiler.source=1.7
     114org.eclipse.jdt.core.javaFormatter=org.eclipse.jdt.core.defaultJavaFormatter
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/Address.java

    r32060 r32211  
    1414import java.awt.event.KeyEvent;
    1515import java.awt.event.MouseEvent;
    16 import java.awt.event.MouseListener;
    17 import java.awt.event.MouseMotionListener;
     16import java.awt.event.WindowAdapter;
    1817import java.awt.event.WindowEvent;
    19 import java.awt.event.WindowListener;
    2018import java.util.ArrayList;
    2119import java.util.Collection;
     
    6361import org.openstreetmap.josm.tools.Shortcut;
    6462
    65 public class Address extends MapMode implements MouseListener, MouseMotionListener, ActionListener {
     63public class Address extends MapMode {
    6664
    6765    // perhaps make all these tags configurable in the future
     
    7674    private String relationMemberHouse = "house";
    7775
    78     private JRadioButton plus_one = new JRadioButton("+1", false);
    79     private JRadioButton plus_two = new JRadioButton("+2", true); // enable this by default
    80     private JRadioButton minus_one = new JRadioButton("-1", false);
    81     private JRadioButton minus_two = new JRadioButton("-2", false);
     76    private JRadioButton plusOne = new JRadioButton("+1", false);
     77    private JRadioButton plusTwo = new JRadioButton("+2", true); // enable this by default
     78    private JRadioButton minusOne = new JRadioButton("-1", false);
     79    private JRadioButton minusTwo = new JRadioButton("-2", false);
    8280    final JCheckBox tagPolygon = new JCheckBox(tr("on polygon"));
    8381
    84     JDialog dialog = null;
    85     JButton clearButton = null;
     82    JDialog dialog;
     83    JButton clearButton;
    8684    final JTextField inputNumber = new JTextField();
    8785    final JTextField inputStreet = new JTextField();
    8886    JLabel link = new JLabel();
    89     private Way selectedWay;
     87    private transient Way selectedWay;
    9088    private boolean shift;
    9189    private boolean ctrl;
     
    114112//        dialog.setVisible(false);
    115113        // kill the window completely to fix an issue on some linux distro and full screen mode.
    116         if(dialog != null)
    117         {
     114        if(dialog != null) {
    118115            dialog.dispose();
    119116            dialog = null;
     
    131128        List<Way> mouseOnExistingWays = new ArrayList<>();
    132129        List<Way> mouseOnExistingBuildingWays = new ArrayList<>();
    133         mouseOnExistingWays = new ArrayList<>();
    134130        Node currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
    135131        if (currentMouseNode != null) {
     
    140136                    && currentMouseNode.get(tagHouseStreet) == null
    141137                    && findWayInRelationAddr(currentMouseNode) == null
    142                     && !inputStreet.getText().equals("")) {
     138                    && !inputStreet.getText().isEmpty()) {
    143139                // house number already present but not linked to a street
    144140                Collection<Command> cmds = new LinkedList<>();
     
    199195                inputNumber.setText("");
    200196                setNewSelection(mouseOnExistingWays.get(0));
    201             } else if (mouseOnExistingWays.size() == 0) {
     197            } else if (mouseOnExistingWays.isEmpty()) {
    202198                // clicked a non highway and not a node => add the new address
    203                 if (inputStreet.getText().equals("") || inputNumber.getText().equals("")) {
     199                if (inputStreet.getText().isEmpty() || inputNumber.getText().isEmpty()) {
    204200                    Toolkit.getDefaultToolkit().beep();
    205201                } else {
     
    217213            }
    218214        }
    219 
    220215    }
    221216
     
    297292    }
    298293
    299     private Node createNewNode(MouseEvent e, Collection<Command> cmds) {
     294    private static Node createNewNode(MouseEvent e, Collection<Command> cmds) {
    300295        // DrawAction.mouseReleased() but without key modifiers
    301296        Node n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
     
    398393
    399394    private static void pruneSuccsAndReverse(List<Integer> is) {
    400         //if (is.size() < 2) return;
    401 
    402395        HashSet<Integer> is2 = new HashSet<>();
    403396        for (int i : is) {
     
    415408        try {
    416409            return ImageProvider.getCursor("crosshair", null);
    417         } catch (Exception e) {
     410        } catch (RuntimeException e) {
     411            Main.warn(e);
    418412        }
    419413        return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
     
    422416    private void applyInputNumberChange() {
    423417        Integer num = Integer.parseInt(inputNumber.getText());
    424         if (plus_one.isSelected())
     418        if (plusOne.isSelected())
    425419            num = num + 1;
    426         if (plus_two.isSelected())
     420        if (plusTwo.isSelected())
    427421            num = num + 2;
    428         if (minus_one.isSelected() && num > 1)
     422        if (minusOne.isSelected() && num > 1)
    429423            num = num - 1;
    430         if (minus_two.isSelected() && num > 2)
     424        if (minusTwo.isSelected() && num > 2)
    431425            num = num - 2;
    432426        inputNumber.setText(num.toString());
     
    435429    private void revertInputNumberChange() {
    436430        Integer num = Integer.parseInt(inputNumber.getText());
    437         if (plus_one.isSelected())
     431        if (plusOne.isSelected())
    438432            num = num - 1;
    439         if (plus_two.isSelected())
     433        if (plusTwo.isSelected())
    440434            num = num - 2;
    441         if (minus_one.isSelected() && num > 1)
     435        if (minusOne.isSelected() && num > 1)
    442436            num = num + 1;
    443         if (minus_two.isSelected() && num > 2)
     437        if (minusTwo.isSelected() && num > 2)
    444438            num = num + 2;
    445439        inputNumber.setText(num.toString());
     
    471465        });
    472466        ButtonGroup bgIncremental = new ButtonGroup();
    473         bgIncremental.add(plus_one);
    474         bgIncremental.add(plus_two);
    475         bgIncremental.add(minus_one);
    476         bgIncremental.add(minus_two);
    477         p.add(minus_one, GBC.std().insets(10, 0, 10, 0));
    478 //        p.add(plus_one, GBC.eol().fill(GBC.HORIZONTAL).insets(10, 0, 0, 0));
    479         p.add(plus_one, GBC.std().insets(0, 0, 10, 0));
     467        bgIncremental.add(plusOne);
     468        bgIncremental.add(plusTwo);
     469        bgIncremental.add(minusOne);
     470        bgIncremental.add(minusTwo);
     471        p.add(minusOne, GBC.std().insets(10, 0, 10, 0));
     472        p.add(plusOne, GBC.std().insets(0, 0, 10, 0));
    480473        tagPolygon.setSelected(Main.pref.getBoolean("cadastrewms.addr.onBuilding", false));
    481474        tagPolygon.addChangeListener(new ChangeListener() {
     
    486479        });
    487480        p.add(tagPolygon, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 0));
    488         p.add(minus_two, GBC.std().insets(10, 0, 10, 0));
    489         p.add(plus_two, GBC.std().insets(0, 0, 10, 0));
     481        p.add(minusTwo, GBC.std().insets(10, 0, 10, 0));
     482        p.add(plusTwo, GBC.std().insets(0, 0, 10, 0));
    490483        p.add(clearButton, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 0));
    491484
     
    508501            }
    509502        });
    510         dialog.addWindowListener(new WindowListener() {
     503        dialog.addWindowListener(new WindowAdapter() {
    511504            @Override
    512             public void windowClosing(WindowEvent arg0) {
     505            public void windowClosing(WindowEvent arg) {
    513506                exitMode();
    514507                Main.map.selectMapMode((MapMode)Main.map.getDefaultButtonAction());
    515508            }
    516             @Override
    517             public void windowClosed(WindowEvent e) {}
    518             @Override
    519             public void windowActivated(WindowEvent arg0) {}
    520             @Override
    521             public void windowDeactivated(WindowEvent arg0) {}
    522             @Override
    523             public void windowDeiconified(WindowEvent arg0) {}
    524             @Override
    525             public void windowIconified(WindowEvent arg0) {}
    526             @Override
    527             public void windowOpened(WindowEvent arg0) {}
    528509        });
    529510        String bounds = Main.pref.get("cadastrewms.addr.bounds",null);
     
    544525    }
    545526
    546     private void setNewSelection(OsmPrimitive osm) {
     527    private static void setNewSelection(OsmPrimitive osm) {
    547528        Collection<OsmPrimitive> newSelection = new LinkedList<>(Main.main.getCurrentDataSet().getSelected());
    548529        newSelection.clear();
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java

    r32163 r32211  
    1313import java.io.OutputStream;
    1414import java.util.ArrayList;
     15import java.util.concurrent.Callable;
    1516import java.util.concurrent.locks.Lock;
    1617import java.util.concurrent.locks.ReentrantLock;
     
    3334public class CacheControl implements Runnable {
    3435
    35     public static final String cLambertCC9Z = "CC";
    36 
    37     public static final String cUTM20N = "UTM";
    38 
    39     public class ObjectOutputStreamAppend extends ObjectOutputStream {
     36    public static final String C_LAMBERT_CC_9Z = "CC";
     37
     38    public static final String C_UTM20N = "UTM";
     39
     40    public static class ObjectOutputStreamAppend extends ObjectOutputStream {
    4041        public ObjectOutputStreamAppend(OutputStream out) throws IOException {
    4142            super(out);
     
    5152    public static int cacheSize = 500;
    5253
    53     public WMSLayer wmsLayer = null;
     54    public WMSLayer wmsLayer;
    5455
    5556    private ArrayList<GeorefImage> imagesToSave = new ArrayList<>();
     
    7980    }
    8081
    81     private void checkDirSize(File path) {
     82    private static void checkDirSize(File path) {
    8283        if (cacheSize != 0) {
    8384            long size = 0;
     
    105106            CadastrePlugin.askToChangeProjection();
    106107        }
    107         try {
    108             File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
    109             if (file.exists()) {
    110                 JOptionPane pane = new JOptionPane(
    111                         tr("Location \"{0}\" found in cache.\n"+
    112                         "Load cache first ?\n"+
    113                         "(No = new cache)", wmsLayer.getName()),
    114                         JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
    115                 // this below is a temporary workaround to fix the "always on top" issue
    116                 JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
    117                 CadastrePlugin.prepareDialog(dialog);
    118                 dialog.setVisible(true);
    119                 int reply = (Integer)pane.getValue();
    120                 // till here
    121 
    122                 if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
    123                     return true;
    124                 } else {
    125                     delete(file);
    126                 }
    127             }
    128         } catch (Exception e) {
    129             Main.error(e);
     108        File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
     109        if (file.exists()) {
     110            int reply = GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
     111                @Override
     112                public Integer call() throws Exception {
     113                    JOptionPane pane = new JOptionPane(
     114                            tr("Location \"{0}\" found in cache.\n"+
     115                            "Load cache first ?\n"+
     116                            "(No = new cache)", wmsLayer.getName()),
     117                            JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
     118                    // this below is a temporary workaround to fix the "always on top" issue
     119                    JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
     120                    CadastrePlugin.prepareDialog(dialog);
     121                    dialog.setVisible(true);
     122                    return (Integer)pane.getValue();
     123                    // till here
     124                }
     125            });
     126
     127            if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
     128                return true;
     129            } else {
     130                delete(file);
     131            }
    130132        }
    131133        return false;
     
    133135
    134136    public void deleteCacheFile() {
    135         try {
    136             delete(new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension()));
    137         } catch (Exception e) {
    138             Main.error(e);
    139         }
    140     }
    141 
    142     private void delete(File file) {
     137        delete(new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension()));
     138    }
     139
     140    private static void delete(File file) {
    143141        Main.info("Delete file "+file);
    144142        if (file.exists())
     
    155153        ) {
    156154            successfulRead = wmsLayer.read(file, ois, currentLambertZone);
    157         } catch (Exception ex) {
     155        } catch (IOException | ClassNotFoundException ex) {
    158156            Main.error(ex);
    159157            GuiHelper.runInEDTAndWait(new Runnable() {
     
    176174        imagesLock.lock();
    177175        this.imagesToSave.add(image);
    178         this.notify();
     176        this.notifyAll();
    179177        imagesLock.unlock();
    180178    }
     
    224222
    225223    private String WMSFileExtension() {
    226         String ext = String.valueOf((wmsLayer.getLambertZone() + 1));
     224        String ext = String.valueOf(wmsLayer.getLambertZone() + 1);
    227225        if (CadastrePlugin.isLambert_cc9())
    228             ext = cLambertCC9Z + ext;
     226            ext = C_LAMBERT_CC_9Z + ext;
    229227        else if (CadastrePlugin.isUtm_france_dom())
    230             ext = cUTM20N + ext;
     228            ext = C_UTM20N + ext;
    231229        return ext;
    232230    }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheFileLambert4ZoneFilter.java

    r18773 r32211  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
     5
    56import java.io.File;
     7import java.util.Locale;
     8
    69import javax.swing.filechooser.FileFilter;
    710
    8 public class CacheFileLambert4ZoneFilter extends FileFilter {
     11public final class CacheFileLambert4ZoneFilter extends FileFilter {
    912
    1013    /**
     
    1417    private final String description;
    1518
    16     public static CacheFileLambert4ZoneFilter[] filters = {
     19    static final CacheFileLambert4ZoneFilter[] filters = {
    1720        new CacheFileLambert4ZoneFilter("1", tr("Lambert Zone {0} cache file (.{0})", 1)),
    1821        new CacheFileLambert4ZoneFilter("2", tr("Lambert Zone {0} cache file (.{0})", 2)),
     
    3134
    3235    public boolean acceptName(String filename) {
    33         String name = filename.toLowerCase();
     36        String name = filename.toLowerCase(Locale.FRANCE);
    3437        for (String ext : extension.split(","))
    3538            if (name.endsWith("." + ext))
     
    4952        return description;
    5053    }
    51 
    5254}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java

    r30859 r32211  
    4343    }
    4444
    45     private URL getURLRaster(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
     45    private static URL getURLRaster(WMSLayer wmsLayer, EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
    4646        // GET /scpc/wms?version=1.1&request=GetMap&layers=CDIF:PMC@QH4480001701&format=image/png&bbox=-1186,0,13555,8830&width=576&height=345&exception=application/vnd.ogc.se_inimage&styles= HTTP/1.1
    4747        final int cRasterX = CadastrePlugin.imageWidth; // keep width constant and adjust width to original image proportions
    48         String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
     48        String str = CadastreInterface.BASE_URL+"/scpc/wms?version=1.1&request=GetMap";
    4949        str += "&layers=CDIF:PMC@";
    5050        str += wmsLayer.getCodeCommune();
     
    6060    }
    6161
    62     private URL buildURLVector(String layers, String styles,
     62    private static URL buildURLVector(String layers, String styles,
    6363            int width, int height,
    6464            EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
    65         String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
     65        String str = CadastreInterface.BASE_URL+"/scpc/wms?version=1.1&request=GetMap";
    6666        str += "&layers="+ layers;
    6767        str += "&format=image/png";
    68         //str += "&format=image/jpeg";
    6968        str += "&bbox="+lambertMin.east()+",";
    7069        str += lambertMin.north() + ",";
     
    7877    }
    7978
    80     private URL getURLVector(EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
     79    private static URL getURLVector(EastNorth lambertMin, EastNorth lambertMax) throws MalformedURLException {
    8180        return buildURLVector(CadastrePlugin.grabLayers, CadastrePlugin.grabStyles,
    8281                CadastrePlugin.imageWidth, CadastrePlugin.imageHeight,
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java

    r32205 r32211  
    1212import java.net.MalformedURLException;
    1313import java.net.URL;
     14import java.nio.charset.StandardCharsets;
     15import java.util.ArrayList;
    1416import java.util.Date;
    15 import java.util.Vector;
     17import java.util.List;
    1618
    1719import javax.swing.JComboBox;
     
    2628
    2729public class CadastreInterface {
    28     public boolean downloadCanceled = false;
    29     public HttpURLConnection urlConn = null;
     30    public boolean downloadCanceled;
     31    public HttpURLConnection urlConn;
    3032
    3133    private String cookie;
    32     private String interfaceRef = null;
    33     private String lastWMSLayerName = null;
     34    private String interfaceRef;
     35    private String lastWMSLayerName;
    3436    private URL searchFormURL;
    35     private Vector<String> listOfCommunes = new Vector<>();
    36     private Vector<String> listOfTA = new Vector<>();
    37     class PlanImage {
     37    private List<String> listOfCommunes = new ArrayList<>();
     38    private List<String> listOfTA = new ArrayList<>();
     39    static class PlanImage {
    3840        String name;
    3941        String ref;
     
    4345        }
    4446    }
    45     private Vector<PlanImage> listOfFeuilles = new Vector<>();
     47    private List<PlanImage> listOfFeuilles = new ArrayList<>();
    4648    private long cookieTimestamp;
    4749
    48     final String baseURL = "http://www.cadastre.gouv.fr";
    49     final String cImageFormat = "Cette commune est au format ";
    50     final String cCommuneListStart = "<select name=\"codeCommune\"";
    51     final String cCommuneListEnd = "</select>";
    52     final String c0ptionListStart = "<option value=\"";
    53     final String cOptionListEnd = "</option>";
    54     final String cBBoxCommunStart = "new GeoBox(";
    55     final String cBBoxCommunEnd = ")";
    56 
    57     final String cInterfaceVector = "afficherCarteCommune.do";
    58     final String cInterfaceRasterTA = "afficherCarteTa.do";
    59     final String cInterfaceRasterFeuille = "afficherCarteFeuille.do";
    60     final String cImageLinkStart = "<a href=\"#\" class=\"raster\" onClick=\"popup('afficherCarteFeuille.do?f=";
    61     final String cTAImageLinkStart = "<a href=\"#\" class=\"raster\" onClick=\"popup('afficherCarteTa.do?f=";
    62     final String cImageNameStart = ">Feuille ";
    63     final String cTAImageNameStart = "Tableau d'assemblage <strong>";
    64 
    65     final static long cCookieExpiration = 30 * 60 * 1000; // 30 minutes expressed in milliseconds
    66 
    67     final  int cRetriesGetCookie = 10; // 10 times every 3 seconds means 30 seconds trying to get a cookie
     50    static final String BASE_URL = "http://www.cadastre.gouv.fr";
     51    static final String C_IMAGE_FORMAT = "Cette commune est au format ";
     52    static final String C_COMMUNE_LIST_START = "<select name=\"codeCommune\"";
     53    static final String C_COMMUNE_LIST_END = "</select>";
     54    static final String C_OPTION_LIST_START = "<option value=\"";
     55    static final String C_OPTION_LIST_END = "</option>";
     56    static final String C_BBOX_COMMUN_START = "new GeoBox(";
     57    static final String C_BBOX_COMMUN_END = ")";
     58
     59    static final String C_INTERFACE_VECTOR = "afficherCarteCommune.do";
     60    static final String C_INTERFACE_RASTER_TA = "afficherCarteTa.do";
     61    static final String C_INTERFACE_RASTER_FEUILLE = "afficherCarteFeuille.do";
     62    static final String C_IMAGE_LINK_START = "<a href=\"#\" class=\"raster\" onClick=\"popup('afficherCarteFeuille.do?f=";
     63    static final String C_TA_IMAGE_LINK_START = "<a href=\"#\" class=\"raster\" onClick=\"popup('afficherCarteTa.do?f=";
     64    static final String C_IMAGE_NAME_START = ">Feuille ";
     65    static final String C_TA_IMAGE_NAME_START = "Tableau d'assemblage <strong>";
     66
     67    static final long COOKIE_EXPIRATION = 30 * 60 * 1000L; // 30 minutes expressed in milliseconds
     68
     69    static final int RETRIES_GET_COOKIE = 10; // 10 times every 3 seconds means 30 seconds trying to get a cookie
    6870
    6971    public boolean retrieveInterface(WMSLayer wmsLayer) throws DuplicateLayerException, WMSException {
    70         if (wmsLayer.getName().equals(""))
     72        if (wmsLayer.getName().isEmpty())
    7173            return false;
    7274        boolean isCookieExpired = isCookieExpired();
     
    9092            openInterface();
    9193        } catch (IOException e) {
     94            Main.error(e);
    9295            JOptionPane.showMessageDialog(Main.parent,
    9396                    tr("Town/city {0} not found or not available\n" +
     
    105108     */
    106109    private void getCookie() throws IOException {
    107         boolean sucess = false;
    108         int retries = cRetriesGetCookie;
     110        boolean success = false;
     111        int retries = RETRIES_GET_COOKIE;
    109112        try {
    110             searchFormURL = new URL(baseURL + "/scpc/accueil.do");
    111             while (sucess == false && retries > 0) {
     113            searchFormURL = new URL(BASE_URL + "/scpc/accueil.do");
     114            while (!success && retries > 0) {
    112115                urlConn = (HttpURLConnection)searchFormURL.openConnection();
    113116                urlConn.setRequestProperty("Connection", "close");
     
    116119                if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    117120                    Main.info("GET "+searchFormURL);
    118                     BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    119                     while(in.readLine() != null) {}  // read the buffer otherwise we sent POST too early
    120                     sucess = true;
     121                    BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8));
     122                    while(in.readLine() != null) {
     123                        // read the buffer otherwise we sent POST too early
     124                    }
     125                    success = true;
    121126                    String headerName;
    122127                    for (int i=1; (headerName = urlConn.getHeaderFieldKey(i))!=null; i++) {
     
    155160    public boolean isCookieExpired() {
    156161        long now = new Date().getTime();
    157         if ((now - cookieTimestamp) > cCookieExpiration) {
     162        if ((now - cookieTimestamp) > COOKIE_EXPIRATION) {
    158163            Main.info("cookie received at "+new Date(cookieTimestamp)+" expired (now is "+new Date(now)+")");
    159164            return true;
     
    182187        // second attempt either from known codeCommune (e.g. from cache) or from ComboBox
    183188        if (interfaceRef == null) {
    184             if (!wmsLayer.getCodeCommune().equals("")) {
     189            if (!wmsLayer.getCodeCommune().isEmpty()) {
    185190                // codeCommune is already known (from previous request or from cache on disk)
    186191                interfaceRef = postForm(wmsLayer, wmsLayer.getCodeCommune());
    187192            } else {
    188193                if (listOfCommunes.size() > 1) {
    189                     // commune unknown, prompt the list of communes from
    190                     // server and try with codeCommune
    191                     String selected = selectMunicipalityDialog(wmsLayer);
     194                    // commune unknown, prompt the list of communes from server and try with codeCommune
     195                    String selected = selectMunicipalityDialog();
    192196                    if (selected != null) {
    193                         String newCodeCommune = selected.substring(1, selected.indexOf(">")-2);
    194                         String newLocation = selected.substring(selected.indexOf(">")+1, selected.lastIndexOf(" - "));
     197                        String newCodeCommune = selected.substring(1, selected.indexOf('>') - 2);
     198                        String newLocation = selected.substring(selected.indexOf('>') + 1, selected.lastIndexOf(" - "));
    195199                        wmsLayer.setCodeCommune(newCodeCommune);
    196200                        wmsLayer.setLocation(newLocation);
     
    205209                    int res = selectFeuilleDialog();
    206210                    if (res != -1) {
    207                         wmsLayer.setCodeCommune(listOfFeuilles.elementAt(res).name);
     211                        wmsLayer.setCodeCommune(listOfFeuilles.get(res).name);
    208212                        checkLayerDuplicates(wmsLayer);
    209213                        interfaceRef = buildRasterFeuilleInterfaceRef(wmsLayer.getCodeCommune());
     
    220224        try {
    221225            // finally, open the interface on server side giving access to the wms server
    222             String lines = null;
    223             String ln = null;
    224             URL interfaceURL = new URL(baseURL + "/scpc/"+interfaceRef);
     226            URL interfaceURL = new URL(BASE_URL + "/scpc/"+interfaceRef);
    225227            urlConn = (HttpURLConnection)interfaceURL.openConnection();
    226228            urlConn.setRequestMethod("GET");
     
    231233            }
    232234            Main.info("GET "+interfaceURL);
    233             BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
     235            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8));
    234236            // read the buffer otherwise we sent POST too early
     237            StringBuilder lines = new StringBuilder();
     238            String ln;
    235239            while ((ln = in.readLine()) != null) {
    236                 lines += ln;
     240                if (Main.isDebugEnabled()) {
     241                    lines.append(ln);
     242                }
    237243            }
    238244            if (Main.isDebugEnabled()) {
    239                 Main.debug(lines);
     245                Main.debug(lines.toString());
    240246            }
    241247        } catch (MalformedURLException e) {
     
    267273    private String postForm(WMSLayer wmsLayer, String codeCommune) throws IOException {
    268274        try {
    269             String ln = null;
    270             String lines = null;
    271275            listOfCommunes.clear();
    272276            listOfTA.clear();
     
    276280            content += "&nomvoie=";
    277281            content += "&lieuDit=";
    278             if (codeCommune == "") {
    279                 content += "&ville=" + new String(java.net.URLEncoder.encode(wmsLayer.getLocation(), "UTF-8"));
     282            if (codeCommune.isEmpty()) {
     283                content += "&ville=" + java.net.URLEncoder.encode(wmsLayer.getLocation(), "UTF-8");
    280284                content += "&codePostal=";
    281285            } else {
     
    286290            content += "&nbResultatParPage=10";
    287291            content += "&x=0&y=0";
    288             searchFormURL = new URL(baseURL + "/scpc/rechercherPlan.do");
     292            searchFormURL = new URL(BASE_URL + "/scpc/rechercherPlan.do");
    289293            urlConn = (HttpURLConnection)searchFormURL.openConnection();
    290294            urlConn.setRequestMethod("POST");
     
    293297            setCookie();
    294298            try (OutputStream wr = urlConn.getOutputStream()) {
    295                 wr.write(content.getBytes());
     299                wr.write(content.getBytes(StandardCharsets.UTF_8));
    296300                Main.info("POST "+content);
    297301                wr.flush();
    298302            }
    299             try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
     303            String ln;
     304            StringBuilder sb = new StringBuilder();
     305            try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8))) {
    300306                while ((ln = rd.readLine()) != null) {
    301                     lines += ln;
    302                 }
    303             }
     307                    sb.append(ln);
     308                }
     309            }
     310            String lines = sb.toString();
    304311            urlConn.disconnect();
    305312            if (lines != null) {
    306                 if (lines.indexOf(cImageFormat) != -1) {
    307                     int i = lines.indexOf(cImageFormat);
    308                     int j = lines.indexOf(".", i);
    309                     wmsLayer.setRaster(lines.substring(i+cImageFormat.length(), j).equals("image"));
    310                 }
    311                 if (!wmsLayer.isRaster() && lines.indexOf(cInterfaceVector) != -1) {  // "afficherCarteCommune.do"
     313                if (lines.indexOf(C_IMAGE_FORMAT) != -1) {
     314                    int i = lines.indexOf(C_IMAGE_FORMAT);
     315                    int j = lines.indexOf('.', i);
     316                    wmsLayer.setRaster("image".equals(lines.substring(i+C_IMAGE_FORMAT.length(), j)));
     317                }
     318                if (!wmsLayer.isRaster() && lines.indexOf(C_INTERFACE_VECTOR) != -1) {  // "afficherCarteCommune.do"
    312319                    // shall be something like: interfaceRef = "afficherCarteCommune.do?c=X2269";
    313                     lines = lines.substring(lines.indexOf(cInterfaceVector),lines.length());
    314                     lines = lines.substring(0, lines.indexOf("'"));
     320                    lines = lines.substring(lines.indexOf(C_INTERFACE_VECTOR),lines.length());
     321                    lines = lines.substring(0, lines.indexOf('\''));
    315322                    Main.info("interface ref.:"+lines);
    316323                    return lines;
    317                 } else if (wmsLayer.isRaster() && lines.indexOf(cInterfaceRasterTA) != -1) { // "afficherCarteTa.do"
     324                } else if (wmsLayer.isRaster() && lines.indexOf(C_INTERFACE_RASTER_TA) != -1) { // "afficherCarteTa.do"
    318325                    // list of values parsed in listOfFeuilles (list all non-georeferenced images)
    319326                    lines = getFeuillesList();
    320327                    if (!downloadCanceled) {
    321328                        parseFeuillesList(lines);
    322                         if (listOfFeuilles.size() > 0) {
     329                        if (!listOfFeuilles.isEmpty()) {
    323330                            int res = selectFeuilleDialog();
    324331                            if (res != -1) {
    325                                 wmsLayer.setCodeCommune(listOfFeuilles.elementAt(res).name);
     332                                wmsLayer.setCodeCommune(listOfFeuilles.get(res).name);
    326333                                checkLayerDuplicates(wmsLayer);
    327334                                interfaceRef = buildRasterFeuilleInterfaceRef(wmsLayer.getCodeCommune());
    328                                 wmsLayer.setCodeCommune(listOfFeuilles.elementAt(res).ref);
    329                                 lines = buildRasterFeuilleInterfaceRef(listOfFeuilles.elementAt(res).ref);
     335                                wmsLayer.setCodeCommune(listOfFeuilles.get(res).ref);
     336                                lines = buildRasterFeuilleInterfaceRef(listOfFeuilles.get(res).ref);
    330337                                Main.info("interface ref.:"+lines);
    331338                                return lines;
     
    334341                    }
    335342                    return null;
    336                 } else if (lines.indexOf(cCommuneListStart) != -1 && lines.indexOf(cCommuneListEnd) != -1) {
     343                } else if (lines.indexOf(C_COMMUNE_LIST_START) != -1 && lines.indexOf(C_COMMUNE_LIST_END) != -1) {
    337344                    // list of values parsed in listOfCommunes
    338                     int i = lines.indexOf(cCommuneListStart);
    339                     int j = lines.indexOf(cCommuneListEnd, i);
     345                    int i = lines.indexOf(C_COMMUNE_LIST_START);
     346                    int j = lines.indexOf(C_COMMUNE_LIST_END, i);
    340347                    parseCommuneList(lines.substring(i, j));
    341348                }
    342349            }
    343350        } catch (MalformedURLException e) {
    344             throw (IOException) new IOException(
    345                 "Illegal url.").initCause(e);
    346         } catch (Exception e){
    347             e.printStackTrace();
     351            throw (IOException) new IOException("Illegal url.").initCause(e);
     352        } catch (DuplicateLayerException e){
     353            Main.error(e);
    348354        }
    349355        return null;
     
    351357
    352358    private void parseCommuneList(String input) {
    353         if (input.indexOf(c0ptionListStart) != -1) {
     359        if (input.indexOf(C_OPTION_LIST_START) != -1) {
    354360            while (input.indexOf("<option value=\"") != -1) {
    355                 int i = input.indexOf(c0ptionListStart);
    356                 int j = input.indexOf(cOptionListEnd, i+c0ptionListStart.length());
    357                 int k = input.indexOf("\"", i+c0ptionListStart.length());
    358                 if (j != -1 && k > (i + c0ptionListStart.length())) {
    359                     String lov = new String(input.substring(i+c0ptionListStart.length()-1, j));
    360                     if (lov.indexOf(">") != -1) {
     361                int i = input.indexOf(C_OPTION_LIST_START);
     362                int j = input.indexOf(C_OPTION_LIST_END, i+C_OPTION_LIST_START.length());
     363                int k = input.indexOf('"', i+C_OPTION_LIST_START.length());
     364                if (j != -1 && k > (i + C_OPTION_LIST_START.length())) {
     365                    String lov = input.substring(i+C_OPTION_LIST_START.length()-1, j);
     366                    if (lov.indexOf('>') != -1) {
    361367                        Main.info("parse "+lov);
    362368                        listOfCommunes.add(lov);
     
    364370                        Main.error("unable to parse commune string:"+lov);
    365371                }
    366                 input = input.substring(j+cOptionListEnd.length());
     372                input = input.substring(j+C_OPTION_LIST_END.length());
    367373            }
    368374        }
     
    372378        // get all images in one html page
    373379        String ln = null;
    374         String lines = null;
     380        StringBuilder lines = new StringBuilder();
    375381        HttpURLConnection urlConn2 = null;
    376382        try {
    377             URL getAllImagesURL = new URL(baseURL + "/scpc/listerFeuillesParcommune.do?keepVolatileSession=&offset=2000");
     383            URL getAllImagesURL = new URL(BASE_URL + "/scpc/listerFeuillesParcommune.do?keepVolatileSession=&offset=2000");
    378384            urlConn2 = (HttpURLConnection)getAllImagesURL.openConnection();
    379385            setCookie(urlConn2);
    380386            urlConn2.connect();
    381387            Main.info("GET "+getAllImagesURL);
    382             try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream()))) {
     388            try (BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn2.getInputStream(), StandardCharsets.UTF_8))) {
    383389                while ((ln = rd.readLine()) != null) {
    384                     lines += ln;
     390                    lines.append(ln);
    385391                }
    386392            }
     
    390396            Main.error(e);
    391397        }
    392         return lines;
     398        return lines.toString();
    393399    }
    394400
     
    398404        String inputTA = input;
    399405        if (Main.pref.getBoolean("cadastrewms.useTA", false)) {
    400             while (inputTA.indexOf(cTAImageLinkStart) != -1) {
    401                 inputTA = inputTA.substring(inputTA.indexOf(cTAImageLinkStart) + cTAImageLinkStart.length());
    402                 String refTA = inputTA.substring(0, inputTA.indexOf("'"));
    403                 String nameTA = inputTA.substring(inputTA.indexOf(cTAImageNameStart) + cTAImageNameStart.length());
    404                 nameTA = nameTA.substring(0, nameTA.indexOf("<"));
     406            while (inputTA.indexOf(C_TA_IMAGE_LINK_START) != -1) {
     407                inputTA = inputTA.substring(inputTA.indexOf(C_TA_IMAGE_LINK_START) + C_TA_IMAGE_LINK_START.length());
     408                String refTA = inputTA.substring(0, inputTA.indexOf('\''));
     409                String nameTA = inputTA.substring(inputTA.indexOf(C_TA_IMAGE_NAME_START) + C_TA_IMAGE_NAME_START.length());
     410                nameTA = nameTA.substring(0, nameTA.indexOf('<'));
    405411                listOfFeuilles.add(new PlanImage(nameTA, refTA));
    406412            }
    407413        }
    408414        // get "Feuilles"
    409         while (input.indexOf(cImageLinkStart) != -1) {
    410             input = input.substring(input.indexOf(cImageLinkStart)+cImageLinkStart.length());
    411             String refFeuille = input.substring(0, input.indexOf("'"));
     415        while (input.indexOf(C_IMAGE_LINK_START) != -1) {
     416            input = input.substring(input.indexOf(C_IMAGE_LINK_START)+C_IMAGE_LINK_START.length());
     417            String refFeuille = input.substring(0, input.indexOf('\''));
    412418            String nameFeuille = input.substring(
    413                     input.indexOf(cImageNameStart)+cImageNameStart.length(),
     419                    input.indexOf(C_IMAGE_NAME_START)+C_IMAGE_NAME_START.length(),
    414420                    input.indexOf(" -"));
    415421            listOfFeuilles.add(new PlanImage(nameFeuille, refFeuille));
     
    417423    }
    418424
    419     private String selectMunicipalityDialog(WMSLayer wmsLayer) {
     425    private String selectMunicipalityDialog() {
    420426        JPanel p = new JPanel(new GridBagLayout());
    421427        String[] communeList = new String[listOfCommunes.size() + 1];
    422428        communeList[0] = tr("Choose from...");
    423429        for (int i = 0; i < listOfCommunes.size(); i++) {
    424             communeList[i + 1] = listOfCommunes.elementAt(i).substring(listOfCommunes.elementAt(i).indexOf(">")+1);
     430            communeList[i + 1] = listOfCommunes.get(i).substring(listOfCommunes.get(i).indexOf('>')+1);
    425431        }
    426432        JComboBox<String> inputCommuneList = new JComboBox<>(communeList);
    427433        p.add(inputCommuneList, GBC.eol().fill(GBC.HORIZONTAL).insets(10, 0, 0, 0));
    428434        JOptionPane pane = new JOptionPane(p, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null);
    429         //pane.createDialog(Main.parent, tr("Select commune")).setVisible(true);
    430435        // this below is a temporary workaround to fix the "always on top" issue
    431436        JDialog dialog = pane.createDialog(Main.parent, tr("Select commune"));
     
    435440        if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(pane.getValue()))
    436441            return null;
    437         return listOfCommunes.elementAt(inputCommuneList.getSelectedIndex()-1);
     442        return listOfCommunes.get(inputCommuneList.getSelectedIndex()-1);
    438443    }
    439444
    440445    private int selectFeuilleDialog() {
    441446        JPanel p = new JPanel(new GridBagLayout());
    442         Vector<String> imageNames = new Vector<>();
     447        List<String> imageNames = new ArrayList<>();
    443448        for (PlanImage src : listOfFeuilles) {
    444449            imageNames.add(src.name);
    445450        }
    446         JComboBox<String> inputFeuilleList = new JComboBox<>(imageNames);
     451        JComboBox<String> inputFeuilleList = new JComboBox<>(imageNames.toArray(new String[]{}));
    447452        p.add(inputFeuilleList, GBC.eol().fill(GBC.HORIZONTAL).insets(10, 0, 0, 0));
    448453        JOptionPane pane = new JOptionPane(p, JOptionPane.INFORMATION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null);
    449         //pane.createDialog(Main.parent, tr("Select Feuille")).setVisible(true);
    450454        // this below is a temporary workaround to fix the "always on top" issue
    451455        JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
     
    455459        if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(pane.getValue()))
    456460            return -1;
    457         int result = inputFeuilleList.getSelectedIndex();
    458         return result;
    459     }
    460 
    461     private String buildRasterFeuilleInterfaceRef(String codeCommune) {
    462         return cInterfaceRasterFeuille + "?f=" + codeCommune;
     461        return inputFeuilleList.getSelectedIndex();
     462    }
     463
     464    private static String buildRasterFeuilleInterfaceRef(String codeCommune) {
     465        return C_INTERFACE_RASTER_FEUILLE + "?f=" + codeCommune;
    463466    }
    464467
     
    474477        if (interfaceRef == null)
    475478            return;
    476         String ln = null;
    477         String line = null;
    478479        // send GET opening normally the small window with the commune overview
    479         String content = baseURL + "/scpc/" + interfaceRef;
     480        String content = BASE_URL + "/scpc/" + interfaceRef;
    480481        content += "&dontSaveLastForward&keepVolatileSession=";
    481482        searchFormURL = new URL(content);
     
    488489        }
    489490        Main.info("GET "+searchFormURL);
    490         try (BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()))) {
     491        String ln;
     492        StringBuilder sb = new StringBuilder();
     493        try (BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), StandardCharsets.UTF_8))) {
    491494            while ((ln = in.readLine()) != null) {
    492                 line += ln;
     495                sb.append(ln);
    493496            }
    494497        }
    495498        urlConn.disconnect();
     499        String line = sb.toString();
    496500        parseBBoxCommune(wmsLayer, line);
    497501        if (wmsLayer.isRaster() && !wmsLayer.isAlreadyGeoreferenced()) {
     
    500504    }
    501505
    502     private void parseBBoxCommune(WMSLayer wmsLayer, String input) {
    503         if (input.indexOf(cBBoxCommunStart) != -1) {
    504             input = input.substring(input.indexOf(cBBoxCommunStart));
    505             int i = input.indexOf(",");
    506             double minx = Double.parseDouble(input.substring(cBBoxCommunStart.length(), i));
    507             int j = input.indexOf(",", i+1);
     506    private static void parseBBoxCommune(WMSLayer wmsLayer, String input) {
     507        if (input.indexOf(C_BBOX_COMMUN_START) != -1) {
     508            input = input.substring(input.indexOf(C_BBOX_COMMUN_START));
     509            int i = input.indexOf(',');
     510            double minx = Double.parseDouble(input.substring(C_BBOX_COMMUN_START.length(), i));
     511            int j = input.indexOf(',', i+1);
    508512            double miny = Double.parseDouble(input.substring(i+1, j));
    509             int k = input.indexOf(",", j+1);
     513            int k = input.indexOf(',', j+1);
    510514            double maxx = Double.parseDouble(input.substring(j+1, k));
    511             int l = input.indexOf(cBBoxCommunEnd, k+1);
     515            int l = input.indexOf(C_BBOX_COMMUN_END, k+1);
    512516            double maxy = Double.parseDouble(input.substring(k+1, l));
    513517            wmsLayer.setCommuneBBox( new EastNorthBound(new EastNorth(minx,miny), new EastNorth(maxx,maxy)));
     
    515519    }
    516520
    517     private void parseGeoreferences(WMSLayer wmsLayer, String input) {
     521    private static void parseGeoreferences(WMSLayer wmsLayer, String input) {
    518522        /* commented since cadastre WMS changes mid july 2013
    519523         * until new GeoBox coordinates parsing is solved */
     
    547551//                wmsLayer.Y0 = Y0;
    548552//            }
    549 //            Main.info("parse georef:"+unknown_yet+","+angle+","+scale_origin+","+dpi+","+fX+","+
    550 //                    fY+","+X0+","+Y0);
     553//            Main.info("parse georef:"+unknown_yet+","+angle+","+scale_origin+","+dpi+","+fX+","+fY+","+X0+","+Y0);
    551554//        }
    552555    }
    553556
    554     private void checkLayerDuplicates(WMSLayer wmsLayer) throws DuplicateLayerException {
     557    private static void checkLayerDuplicates(WMSLayer wmsLayer) throws DuplicateLayerException {
    555558        if (Main.map != null) {
    556559            for (Layer l : Main.map.mapView.getAllLayers()) {
    557                 if (l instanceof WMSLayer && l.getName().equals(wmsLayer.getName()) && (l != wmsLayer)) {
     560                if (l instanceof WMSLayer && l.getName().equals(wmsLayer.getName()) && (!l.equals(wmsLayer))) {
    558561                    Main.info("Try to grab into a new layer when "+wmsLayer.getName()+" is already opened.");
    559562                    // remove the duplicated layer
     
    569572            urlConn.setConnectTimeout(1);
    570573            urlConn.setReadTimeout(1);
    571             //urlConn.disconnect();
    572574        }
    573575        downloadCanceled = true;
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionImporter.java

    r30738 r32211  
    4141            fileStr = URLDecoder.decode(fileStr, "UTF-8");
    4242            fileStr = fileStr.substring(fileStr.indexOf(":/")+2);
    43             String filename = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length());
    44             String ext = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length());
     43            String filename = fileStr.substring(fileStr.lastIndexOf('/')+1,fileStr.length());
     44            String ext = (filename.lastIndexOf('.')==-1)?"":filename.substring(filename.lastIndexOf('.')+1,filename.length());
    4545            // create layer and load cache
    46             if (ext.length() == 3 && ext.substring(0, CacheControl.cLambertCC9Z.length()).equals(CacheControl.cLambertCC9Z))
     46            if (ext.length() == 3 && ext.substring(0, CacheControl.C_LAMBERT_CC_9Z.length()).equals(CacheControl.C_LAMBERT_CC_9Z))
    4747                ext = ext.substring(2);
    48             else if (ext.length() == 4 && ext.substring(0, CacheControl.cUTM20N.length()).equals(CacheControl.cUTM20N))
     48            else if (ext.length() == 4 && ext.substring(0, CacheControl.C_UTM20N.length()).equals(CacheControl.C_UTM20N))
    4949                ext = ext.substring(3);
    5050            else if (ext.length() == 2 || ext.length() > 4)
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java

    r32060 r32211  
    1414import java.net.MalformedURLException;
    1515import java.net.URL;
     16import java.nio.charset.StandardCharsets;
    1617import java.util.ArrayList;
    1718import java.util.Collection;
     
    3839    private WMSLayer wmsLayer;
    3940    private CadastreInterface wmsInterface;
    40     private String svg = null;
    41     private static EastNorthBound currentView = null;
    42     private EastNorthBound viewBox = null;
     41    private String svg;
     42    private static EastNorthBound currentView;
     43    private EastNorthBound viewBox;
    4344    private static String errorMessage;
    4445
     
    8283    @Override
    8384    protected void finish() {
     85        // Do nothing
    8486    }
    8587
     
    119121                // check if new node is not already created by another new path
    120122                Node nearestNewNode = checkNearestNode(nodeToAdd, svgDataSet.getNodes());
    121                 if (nearestNewNode == nodeToAdd)
     123                if (nodeToAdd.equals(nearestNewNode))
    122124                    svgDataSet.addPrimitive(nearestNewNode);
    123125                wayToAdd.addNode(nearestNewNode); // either a new node or an existing one
     
    175177        double dy = Double.parseDouble(coor[2]);
    176178        for (int i=3; i<coor.length; i+=2){
    177             if (coor[i].equals("")) {
     179            if (coor[i].isEmpty()) {
    178180                eastNorth.clear(); // some paths are just artifacts
    179181                return;
     
    197199     * @return the already existing node (if any), otherwise the new node candidate.
    198200     */
    199     private Node checkNearestNode(Node nodeToAdd, Collection<Node> nodes) {
     201    private static Node checkNearestNode(Node nodeToAdd, Collection<Node> nodes) {
    200202        double epsilon = 0.05; // smallest distance considering duplicate node
    201203        for (Node n : nodes) {
     
    220222    }
    221223
    222     private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
    223         String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
     224    private static URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
     225        String str = CadastreInterface.BASE_URL+"/scpc/wms?version=1.1&request=GetMap";
    224226        str += "&layers=";
    225227        str += "CDIF:LS2";
     
    243245        wmsInterface.setCookie();
    244246        File file = new File(CadastrePlugin.cacheDir + "building.svg");
    245         String svg = new String();
     247        String svg = "";
    246248        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
    247249            if (file.exists())
    248250                file.delete();
    249251            try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
    250                  InputStreamReader isr = new InputStreamReader(is);
     252                 InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
    251253                 BufferedReader br = new BufferedReader(isr)) {
    252                 String line="";
     254                String line;
    253255                while ( null!=(line=br.readLine())){
    254256                    line += "\n";
    255                     bos.write(line.getBytes());
     257                    bos.write(line.getBytes(StandardCharsets.UTF_8));
    256258                    svg += line;
    257259                }
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java

    r32060 r32211  
    1414import java.net.MalformedURLException;
    1515import java.net.URL;
     16import java.nio.charset.StandardCharsets;
    1617import java.util.ArrayList;
    1718import java.util.Collection;
     
    4344    private WMSLayer wmsLayer;
    4445    private CadastreInterface wmsInterface;
    45     private String svg = null;
    46     private EastNorthBound viewBox = null;
     46    private String svg;
     47    private EastNorthBound viewBox;
    4748    private static String errorMessage;
    4849
     
    8889    @Override
    8990    protected void finish() {
     91        // Do nothing
    9092    }
    9193
     
    168170    private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
    169171        try {
    170             URL url = null;
    171             url = getURLsvg(bbox);
    172             return grabSVG(url);
     172            return grabSVG(getURLsvg(bbox));
    173173        } catch (MalformedURLException e) {
    174174            throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
     
    176176    }
    177177
    178     private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
    179         String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
     178    private static URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
     179        String str = CadastreInterface.BASE_URL+"/scpc/wms?version=1.1&request=GetMap";
    180180        str += "&layers=";
    181181        str += "CDIF:COMMUNE";
     
    198198        wmsInterface.setCookie();
    199199        File file = new File(CadastrePlugin.cacheDir + "boundary.svg");
    200         String svg = new String();
     200        String svg = "";
    201201        try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
    202202            if (file.exists())
     
    205205                 InputStreamReader isr =new InputStreamReader(is);
    206206                 BufferedReader br = new BufferedReader(isr)) {
    207                 String line="";
     207                String line;
    208208                while ( null!=(line=br.readLine())){
    209209                    line += "\n";
    210                     bos.write(line.getBytes());
     210                    bos.write(line.getBytes(StandardCharsets.UTF_8));
    211211                    svg += line;
    212212                }
     
    219219
    220220    public static void download(WMSLayer wmsLayer) {
    221         if (CadastrePlugin.autoSourcing == false) {
     221        if (!CadastrePlugin.autoSourcing) {
    222222            JOptionPane.showMessageDialog(Main.parent,
    223223                    tr("Please, enable auto-sourcing and check cadastre millesime."));
     
    228228            JOptionPane.showMessageDialog(Main.parent, errorMessage);
    229229    }
    230 
    231230}
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/MenuActionLoadFromCache.java

    r32060 r32211  
    1818    private static final long serialVersionUID = 1L;
    1919
    20     public static String name = marktr("Load layer from cache");
     20    public static final String name = marktr("Load layer from cache");
    2121
     22    /**
     23     * Constructs a new {@code MenuActionLoadFromCache}.
     24     */
    2225    public MenuActionLoadFromCache() {
    2326        super(tr(name), "cadastre_small", tr("Load location from cache (only if cache is enabled)"), null, false, "cadastrefr/loadfromcache", true);
     
    3639            if (file.exists()) {
    3740                String filename = file.getName();
    38                 String ext = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length());
    39                 if ((ext.length() == 3 && ext.substring(0, CacheControl.cLambertCC9Z.length()).equals(CacheControl.cLambertCC9Z) &&
     41                String ext = (filename.lastIndexOf('.')==-1)?"":filename.substring(filename.lastIndexOf('.')+1,filename.length());
     42                if ((ext.length() == 3 && ext.substring(0, CacheControl.C_LAMBERT_CC_9Z.length()).equals(CacheControl.C_LAMBERT_CC_9Z) &&
    4043                    !(CadastrePlugin.isLambert_cc9()))
    41                     || (ext.length() == 4 && ext.substring(0, CacheControl.cUTM20N.length()).equals(CacheControl.cUTM20N) &&
     44                    || (ext.length() == 4 && ext.substring(0, CacheControl.C_UTM20N.length()).equals(CacheControl.C_UTM20N) &&
    4245                            !(CadastrePlugin.isUtm_france_dom()))
    4346                    || (ext.length() == 1) && !(CadastrePlugin.isLambert())) {
     
    4548                        continue;
    4649                } else {
    47                     String location = filename.substring(0, filename.lastIndexOf("."));
    48                     if (ext.length() == 3 && ext.substring(0, CacheControl.cLambertCC9Z.length()).equals(CacheControl.cLambertCC9Z))
     50                    String location = filename.substring(0, filename.lastIndexOf('.'));
     51                    if (ext.length() == 3 && ext.substring(0, CacheControl.C_LAMBERT_CC_9Z.length()).equals(CacheControl.C_LAMBERT_CC_9Z))
    4952                        ext = ext.substring(2);
    50                     else if (ext.length() == 4 && ext.substring(0, CacheControl.cUTM20N.length()).equals(CacheControl.cUTM20N))
     53                    else if (ext.length() == 4 && ext.substring(0, CacheControl.C_UTM20N.length()).equals(CacheControl.C_UTM20N))
    5154                        ext = ext.substring(3);
    5255                    // check the extension and its compatibility with current projection
  • applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java

    r32060 r32211  
    2121import java.util.ArrayList;
    2222import java.util.HashSet;
     23import java.util.Locale;
    2324import java.util.Vector;
    2425import java.util.concurrent.locks.Lock;
     
    3940import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
    4041import org.openstreetmap.josm.gui.layer.Layer;
     42import org.openstreetmap.josm.gui.util.GuiHelper;
    4143
    4244/**
     
    7779    public EastNorthBound communeBBox = new EastNorthBound(new EastNorth(0,0), new EastNorth(0,0));
    7880
    79     private boolean isRaster = false;
    80     private boolean isAlreadyGeoreferenced = false;
     81    private boolean isRaster;
     82    private boolean isAlreadyGeoreferenced;
    8183    public double X0, Y0, angle, fX, fY;
    8284
     
    8789
    8890    // offset for vector images temporarily shifted (correcting Cadastre artifacts), in pixels
    89     public double deltaEast=0;
    90     public double deltaNorth=0;
     91    public double deltaEast;
     92    public double deltaNorth;
    9193
    9294    private Action saveAsPng;
     
    107109            Main.map.mapView.repaint();
    108110        }
    109 
    110111    }
    111112
     
    114115    public GrabThread grabThread;
    115116
     117    /**
     118     * Constructs a new {@code WMSLayer}.
     119     */
    116120    public WMSLayer() {
    117121        this(tr("Blank Layer"), "", -1);
     
    142146
    143147    private static String buildName(String location, String codeCommune) {
    144         String ret = location.toUpperCase();
    145         if (codeCommune != null && !codeCommune.equals(""))
     148        String ret = location.toUpperCase(Locale.FRANCE);
     149        if (codeCommune != null && !codeCommune.isEmpty())
    146150            ret += "(" + codeCommune + ")";
    147151        return  ret;
     
    149153
    150154    private String rebuildName() {
    151         return buildName(this.location.toUpperCase(), this.codeCommune);
     155        return buildName(this.location.toUpperCase(Locale.FRANCE), this.codeCommune);
    152156    }
    153157
     
    157161        // if it is the first layer, use the communeBBox as grab bbox (and not divided)
    158162        if (Main.map.mapView.getAllLayers().size() == 1 ) {
    159             b = this.getCommuneBBox().toBounds();
    160             Main.map.mapView.zoomTo(b);
    161             divideBbox(b, 1);
     163            final Bounds bounds = this.getCommuneBBox().toBounds();
     164            GuiHelper.runInEDTAndWait(new Runnable() {
     165                @Override
     166                public void run() {
     167                    Main.map.mapView.zoomTo(bounds);
     168                }
     169            });
     170            divideBbox(bounds, 1);
    162171        } else {
    163172            if (isRaster) {
    164                 b = new Bounds(Main.getProjection().eastNorth2latlon(rasterMin), Main.getProjection().eastNorth2latlon(rasterMax));
    165                 divideBbox(b, Integer.parseInt(Main.pref.get("cadastrewms.rasterDivider",
    166                         CadastrePreferenceSetting.DEFAULT_RASTER_DIVIDER)));
     173                divideBbox(new Bounds(Main.getProjection().eastNorth2latlon(rasterMin), Main.getProjection().eastNorth2latlon(rasterMax)),
     174                        Integer.parseInt(Main.pref.get("cadastrewms.rasterDivider", CadastrePreferenceSetting.DEFAULT_RASTER_DIVIDER)));
    167175            } else
    168                 divideBbox(b, Integer.parseInt(Main.pref.get("cadastrewms.scale", CadastrePreferenceSetting.DEFAULT_GRAB_MULTIPLIER)));
     176                divideBbox(b,
     177                        Integer.parseInt(Main.pref.get("cadastrewms.scale", CadastrePreferenceSetting.DEFAULT_GRAB_MULTIPLIER)));
    169178        }
    170179        grabThread.addImages(dividedBbox);
     
    223232                    j = 0;
    224233                    currDir = (currDir+1)%4;
    225                 } else if (currDir >= 0 && j >= (currDir == 0 || currDir == 2 ? x-1 : y-1)) {
     234                } else if (currDir >= 0 && j >= (currDir == 0 || currDir == 2 ? (x-1) : (y-1))) {
    226235                    // the overall is a rectangle, not a square. Jump to the other side to grab next square.
    227236                    k++;
     
    251260            str += "\n"+tr("Is not vectorized.");
    252261            str += "\n"+tr("Bounding box: {0}", communeBBox);
    253             if(images.size()>0)
     262            if(!images.isEmpty())
    254263                str += "\n"+tr("Image size (px): {0}/{1}", images.get(0).image.getWidth(), images.get(0).image.getHeight());
    255         } else
     264        } else {
    256265            str += "\n"+tr("Is vectorized.");
    257266            str += "\n"+tr("Commune bbox: {0}", communeBBox);
     267        }
    258268        return str;
    259269    }
     
    266276    @Override
    267277    public void mergeFrom(Layer from) {
     278        // Do nothing
    268279    }
    269280
     
    318329        refineGeoRef.setEnabled(isRaster && grabThread.getImagesToGrabSize() == 0);
    319330        Action resetOffset = new ResetOffsetActionMenu();
    320         resetOffset.setEnabled(!isRaster && images.size() > 0 && (deltaEast!=0.0 || deltaNorth!=0.0));
     331        resetOffset.setEnabled(!isRaster && !images.isEmpty() && (deltaEast!=0.0 || deltaNorth!=0.0));
    321332        return new Action[] {
    322333                LayerListDialog.getInstance().createShowHideLayerAction(),
     
    328339                resetOffset,
    329340                new LayerListPopup.InfoAction(this),
    330 
    331341        };
    332342    }
     
    368378        return minX+","+minY+","+maxX+","+maxY;
    369379    }
    370 
    371380
    372381    public String getLocation() {
     
    548557            int newWidth = oldImgWidth*lx.size();
    549558            int newHeight = oldImgHeight*ly.size();
    550             BufferedImage new_img = new BufferedImage(newWidth, newHeight, images.get(0).image.getType()/*BufferedImage.TYPE_INT_ARGB*/);
    551             Graphics g = new_img.getGraphics();
     559            BufferedImage newImg = new BufferedImage(newWidth, newHeight, images.get(0).image.getType()/*BufferedImage.TYPE_INT_ARGB*/);
     560            Graphics g = newImg.getGraphics();
    552561            // Coordinate (0,0) is on top,left corner where images are grabbed from bottom left
    553562            int rasterDivider = (int)Math.sqrt(images.size());
     
    562571            synchronized(this) {
    563572                images.clear();
    564                 images.add(new GeorefImage(new_img, min, max, this));
     573                images.add(new GeorefImage(newImg, min, max, this));
    565574            }
    566575        }
     
    586595        rasterMin = adj1;
    587596        rasterMax = adj2;
    588         setCommuneBBox(new EastNorthBound(new EastNorth(0,0), new EastNorth(images.get(0).image.getWidth()-1,images.get(0).image.getHeight()-1)));
     597        setCommuneBBox(new EastNorthBound(
     598                new EastNorth(0,0),
     599                new EastNorth(images.get(0).image.getWidth()-1,images.get(0).image.getHeight()-1)));
    589600        rasterRatio = (rasterMax.getX()-rasterMin.getX())/(communeBBox.max.getX() - communeBBox.min.getX());
    590601    }
     
    598609            return communeBBox;
    599610        }
    600         double min_x = Double.MAX_VALUE;
    601         double max_x = Double.MIN_VALUE;
    602         double min_y = Double.MAX_VALUE;
    603         double max_y = Double.MIN_VALUE;
     611        double minX = Double.MAX_VALUE;
     612        double maxX = Double.MIN_VALUE;
     613        double minY = Double.MAX_VALUE;
     614        double maxY = Double.MIN_VALUE;
    604615        for (GeorefImage image:images){
    605             min_x = image.min.east() < min_x ? image.min.east() : min_x;
    606             max_x = image.max.east() > max_x ? image.max.east() : max_x;
    607             min_y = image.min.north() < min_y ? image.min.north() : min_y;
    608             max_y = image.max.north() > max_y ? image.max.north() : max_y;
    609         }
    610         EastNorthBound maxGrabbedBBox = new EastNorthBound(new EastNorth(min_x, min_y), new EastNorth(max_x, max_y));
    611         return maxGrabbedBBox;
     616            minX = image.min.east() < minX ? image.min.east() : minX;
     617            maxX = image.max.east() > maxX ? image.max.east() : maxX;
     618            minY = image.min.north() < minY ? image.min.north() : minY;
     619            maxY = image.max.north() > maxY ? image.max.north() : maxY;
     620        }
     621        return new EastNorthBound(new EastNorth(minX, minY), new EastNorth(maxX, maxY));
    612622    }
    613623
     
    653663        this.rasterMin = rasterMin.rotate(rasterCenter, angle);
    654664        this.rasterMax = rasterMax.rotate(rasterCenter, angle);
    655 //        double proportion = dst1.distance(dst2)/org1.distance(org2);
    656665        images.get(0).rotate(rasterCenter, angle);
    657666        this.angle += angle;
     
    718727        imagesLock.unlock();
    719728    }
    720 
    721729}
Note: See TracChangeset for help on using the changeset viewer.