Changeset 30738 in osm
- Timestamp:
- 2014-10-19T01:27:04+02:00 (10 years ago)
- 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 411 411 try { 412 412 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 } 418 419 } catch (Exception ex) { 419 420 logger.log(Level.SEVERE, ex.getMessage()); … … 534 535 } 535 536 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 544 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) { 557 558 logger.log(Level.SEVERE, ex.getMessage()); 558 559 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 { 566 565 567 566 @Override -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/ImportImagePlugin.java
r29805 r30738 95 95 // add menu entries 96 96 //Main.main.menu.fileMenu.insert(loadFileAction, 8); 97 97 98 98 //Main.main.menu.fileMenu.insertSeparator(9); 99 99 100 100 ExtensionFileFilter.importers.add(new ImportImageFileImporter()); 101 101 … … 129 129 130 130 // if properties file doesn't exist, install plugin 131 if(!isInstalled) 132 { 131 if (!isInstalled) { 133 132 134 133 /*----------- Begin installation ---------------*/ … … 147 146 148 147 // 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 } 157 155 logger.debug("Plugin properties loaded"); 158 156 } 159 157 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 } 168 165 logger.debug("Logging properties created"); 169 166 } … … 172 169 } 173 170 } 174 175 171 176 172 /** -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/LayerPropertiesDialog.java
r30532 r30738 31 31 import org.opengis.referencing.NoSuchAuthorityCodeException; 32 32 import org.opengis.referencing.crs.CoordinateReferenceSystem; 33 import org.openstreetmap.josm.Main; 33 34 34 35 /** … … 36 37 * - general and spatial information about the georeferenced image 37 38 * - a possiblitly to change the source reference system of the image 38 * 39 * 39 * 40 * 40 41 * @author Christoph Beekmans, Fabian Kowitz, Anna Robaszkiewicz, Oliver Kuhn, Martin Ulitzny 41 42 * 42 43 */ 43 44 public class LayerPropertiesDialog extends JFrame{ 44 45 45 46 private Vector<String> supportedCRS; 46 47 private ImageLayer imageLayer; … … 86 87 87 88 /** 88 * This method initializes 89 * 89 * This method initializes 90 * 90 91 */ 91 92 public LayerPropertiesDialog(ImageLayer imageLayer, Vector<String> supportedCRS) { … … 95 96 initialize(); 96 97 } 97 98 /** 99 * This method initializes 100 * 98 99 /** 100 * This method initializes 101 * 101 102 */ 102 103 public LayerPropertiesDialog(Vector<String> supportedCRS) { … … 105 106 initialize(); 106 107 } 107 108 108 109 109 110 /** 110 111 * This method initializes this 111 * 112 * 112 113 */ 113 114 private void initialize() { … … 115 116 this.setContentPane(getMainPanel()); 116 117 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 124 125 */ 125 126 private JPanel getMainPanel() { … … 134 135 135 136 /** 136 * This method initializes jPanel 137 * 138 * @return javax.swing.JPanel 137 * This method initializes jPanel 138 * 139 * @return javax.swing.JPanel 139 140 */ 140 141 private JPanel getJPanel() { … … 155 156 156 157 /** 157 * This method initializes buttonPanel 158 * 159 * @return javax.swing.JPanel 158 * This method initializes buttonPanel 159 * 160 * @return javax.swing.JPanel 160 161 */ 161 162 private JPanel getButtonPanel() { … … 170 171 171 172 /** 172 * This method initializes jTabbedPane 173 * 174 * @return javax.swing.JTabbedPane 173 * This method initializes jTabbedPane 174 * 175 * @return javax.swing.JTabbedPane 175 176 */ 176 177 private JTabbedPane getJTabbedPane() { … … 184 185 185 186 /** 186 * This method initializes infoPanel 187 * 188 * @return javax.swing.JPanel 187 * This method initializes infoPanel 188 * 189 * @return javax.swing.JPanel 189 190 */ 190 191 private JPanel getInfoPanel() { … … 226 227 crsValueLabel = new JLabel(); 227 228 crsValueLabel.setBounds(new Rectangle(150, 150, 226, 16)); 228 229 229 230 String crsDescription = ""; 230 231 try { … … 233 234 } 234 235 crsValueLabel.setText(crsDescription + "(" + imageLayer.getBbox().getCoordinateReferenceSystem().getName().toString() + ")"); 235 236 236 237 crsLabel = new JLabel(); 237 238 crsLabel.setBounds(new Rectangle(15, 150, 118, 16)); … … 281 282 282 283 /** 283 * This method initializes crsPanel 284 * 285 * @return javax.swing.JPanel 284 * This method initializes crsPanel 285 * 286 * @return javax.swing.JPanel 286 287 */ 287 288 private JPanel getCrsPanel() { … … 295 296 } 296 297 currentCRSValueLabel.setText(crsDescription); 297 298 298 299 currentCRSLabel = new JLabel(); 299 300 currentCRSLabel.setBounds(new Rectangle(15, 33, 52, 16)); … … 339 340 340 341 /** 341 * This method initializes okButton 342 * 343 * @return javax.swing.JButton 342 * This method initializes okButton 343 * 344 * @return javax.swing.JButton 344 345 */ 345 346 private JButton getOkButton() { … … 349 350 okButton.setText("OK"); 350 351 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 353 355 setVisible(false); 354 356 dispose(); … … 360 362 361 363 /** 362 * This method initializes searchField 363 * 364 * @return javax.swing.JTextField 364 * This method initializes searchField 365 * 366 * @return javax.swing.JTextField 365 367 */ 366 368 private JTextField getSearchField() { … … 370 372 searchField.setToolTipText("Enter keywords or EPSG codes"); 371 373 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 374 377 for (Iterator<String> iterator = supportedCRS.iterator(); iterator.hasNext();) { 375 String type = (String)iterator.next();378 String type = iterator.next(); 376 379 if (type.contains(searchField.getText())) { 377 380 crsJList.setSelectedIndex(supportedCRS.indexOf(type)); … … 379 382 break; 380 383 } 381 384 382 385 } 383 386 } … … 388 391 389 392 /** 390 * This method initializes crsListScrollPane 391 * 392 * @return javax.swing.JScrollPane 393 * This method initializes crsListScrollPane 394 * 395 * @return javax.swing.JScrollPane 393 396 */ 394 397 private JScrollPane getCrsListScrollPane() { … … 402 405 403 406 /** 404 * This method initializes crsJList 405 * 406 * @return javax.swing.JList 407 * This method initializes crsJList 408 * 409 * @return javax.swing.JList 407 410 */ 408 411 private JList<String> getCrsJList() { … … 415 418 416 419 /** 417 * This method initializes useDefaultCRSButton 418 * 419 * @return javax.swing.JButton 420 * This method initializes useDefaultCRSButton 421 * 422 * @return javax.swing.JButton 420 423 */ 421 424 private JButton getUseDefaultCRSButton() { … … 425 428 useDefaultCRSButton.setText("Apply Default"); 426 429 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 429 433 try { 430 434 431 435 setCursor(new Cursor(Cursor.WAIT_CURSOR)); 432 436 if(PluginOperations.defaultSourceCRS != null){ … … 436 440 JOptionPane.showMessageDialog(getContentPane(), "<html>No default reference system available.<br>Please select one from the list</html>"); 437 441 } 438 442 439 443 } catch (NoSuchAuthorityCodeException e1) { 440 444 // TODO Auto-generated catch block … … 457 461 458 462 /** 459 * This method initializes applySelectedCRSButton 460 * 461 * @return javax.swing.JButton 463 * This method initializes applySelectedCRSButton 464 * 465 * @return javax.swing.JButton 462 466 */ 463 467 private JButton getApplySelectedCRSButton() { … … 469 473 applySelectedCRSButton.setText("<html>Apply<br>Selection</html>"); 470 474 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(); 474 479 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]")); 475 480 476 481 CoordinateReferenceSystem newRefSys = null; 477 482 try { 478 483 newRefSys = CRS.decode(code, eastingFirstCheckBox.isSelected()); 479 484 480 485 setCursor(new Cursor(Cursor.WAIT_CURSOR)); 481 486 482 487 imageLayer.resample(newRefSys); 483 488 … … 495 500 setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); 496 501 } 497 498 502 503 499 504 } 500 505 }); … … 504 509 505 510 /** 506 * This method initializes setSelectedCRSAsDefaultButton 507 * 508 * @return javax.swing.JButton 511 * This method initializes setSelectedCRSAsDefaultButton 512 * 513 * @return javax.swing.JButton 509 514 */ 510 515 private JButton getSetSelectedCRSAsDefaultButton() { … … 515 520 setSelectedCRSAsDefaultButton 516 521 .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 519 525 if(crsJList.getSelectedValue() != null){ 520 String selection = (String)crsJList.getSelectedValue();526 String selection = crsJList.getSelectedValue(); 521 527 String code = selection.substring(selection.indexOf("[-") + 2, selection.indexOf("-]")); 522 528 523 529 try { 524 530 PluginOperations.defaultSourceCRS = CRS.decode(code, eastingFirstCheckBox.isSelected()); 525 531 PluginOperations.defaultSourceCRSDescription = selection; 526 532 527 533 ImportImagePlugin.pluginProps.setProperty("default_crs_eastingfirst", "" + eastingFirstCheckBox.isSelected()); 528 534 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 533 539 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); 544 543 } 545 } else{544 } else { 546 545 JOptionPane.showMessageDialog(getContentPane(), "Please make a selection from the list."); 547 546 } 548 549 550 547 } 551 548 }); … … 553 550 return setSelectedCRSAsDefaultButton; 554 551 } 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 560 557 */ 561 558 private JCheckBox getEastingFirstCheckBox() { … … 568 565 } 569 566 570 571 567 568 572 569 /** 573 570 * Listener setting text in the search field if selection has changed. … … 575 572 */ 576 573 class ListSelectionHandler implements ListSelectionListener { 577 public void valueChanged(ListSelectionEvent e) { 574 @Override 575 public void valueChanged(ListSelectionEvent e) { 578 576 if(e.getValueIsAdjusting()) 579 577 { -
applications/editors/josm/plugins/ImportImagePlugin/src/org/openstreetmap/josm/plugins/ImportImagePlugin/PluginOperations.java
r30737 r30738 296 296 logger.debug("Loading .prj file: " + prjFile.getAbsolutePath()); 297 297 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 } 307 304 refSys = CRS.parseWKT(sb.toString().trim()); 308 305 } catch (FactoryException e) { -
applications/editors/josm/plugins/NanoLog/src/nanolog/NanoLogLayer.java
r30737 r30738 103 103 final SimpleDateFormat fmt = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SS"); 104 104 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 } 139 139 return result; 140 140 } -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java
r30737 r30738 1 1 // License: GPL. v2 and later. Copyright 2008-2009 by Pieren <pieren3@gmail.com> and others 2 2 package cadastre_fr; 3 4 import static org.openstreetmap.josm.tools.I18n.tr; 5 6 import java.io.BufferedOutputStream; 7 import java.io.File; 8 import java.io.FileInputStream; 9 import java.io.FileOutputStream; 10 import java.io.IOException; 11 import java.io.ObjectInputStream; 12 import java.io.ObjectOutputStream; 13 import java.io.OutputStream; 14 import java.util.ArrayList; 15 import java.util.concurrent.locks.Lock; 16 import java.util.concurrent.locks.ReentrantLock; 17 18 import javax.swing.JDialog; 19 import javax.swing.JOptionPane; 20 21 import org.openstreetmap.josm.Main; 22 3 23 /** 4 24 * This class handles the WMS layer cache mechanism. The design is oriented for a good performance (no … … 10 30 * is inserted before each append and an exception is raised at objects read). 11 31 */ 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 24 32 public class CacheControl implements Runnable { 25 33 … … 32 40 super(out); 33 41 } 42 @Override 34 43 protected void writeStreamHeader() throws IOException { 35 44 reset(); … … 40 49 41 50 public static int cacheSize = 500; 42 43 51 44 52 public WMSLayer wmsLayer = null; … … 141 149 public boolean loadCache(File file, int currentLambertZone) { 142 150 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 ) { 148 155 successfulRead = wmsLayer.read(file, ois, currentLambertZone); 149 156 } catch (Exception ex) { … … 151 158 JOptionPane.showMessageDialog(Main.parent, tr("Error loading file.\nProbably an old version of the cache file."), tr("Error"), JOptionPane.ERROR_MESSAGE); 152 159 return false; 153 } finally {154 try {155 ois.close();156 fis.close();157 } catch (Exception e) {158 e.printStackTrace();159 }160 160 } 161 161 if (successfulRead && wmsLayer.isRaster()) { … … 165 165 return successfulRead; 166 166 } 167 168 167 169 168 public synchronized void saveCache(GeorefImage image) { … … 177 176 * Thread saving the grabbed images in background. 178 177 */ 178 @Override 179 179 public synchronized void run() { 180 180 for (;;) { … … 186 186 try { 187 187 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 } 192 193 } 193 oos.close();194 194 } 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 } 200 201 } 201 oos.close();202 202 } 203 203 } catch (IOException e) { 204 e.printStackTrace(System.out);204 Main.error(e); 205 205 } 206 206 imagesLock.lock(); -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreGrabber.java
r28961 r30738 22 22 private CadastreInterface wmsInterface = new CadastreInterface(); 23 23 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 { 26 26 try { 27 27 URL url = null; … … 88 88 wmsInterface.urlConn.setRequestMethod("GET"); 89 89 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 } 94 93 } 95 94 … … 97 96 return wmsInterface; 98 97 } 99 100 98 } -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreInterface.java
r30737 r30738 229 229 } 230 230 if (Main.isDebugEnabled()) { 231 231 Main.debug(lines); 232 232 } 233 233 } catch (MalformedURLException e) { … … 284 284 urlConn.setDoInput(true); 285 285 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 } 296 296 urlConn.disconnect(); 297 297 if (lines != null) { … … 371 371 setCookie(urlConn2); 372 372 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 } 379 379 urlConn2.disconnect(); 380 //System.out.println("GET="+lines);381 380 } catch (IOException e) { 382 381 listOfFeuilles.clear(); 383 e.printStackTrace();382 Main.error(e); 384 383 } 385 384 return lines; … … 483 482 } 484 483 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 } 490 489 urlConn.disconnect(); 491 490 parseBBoxCommune(wmsLayer, line); … … 511 510 512 511 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 514 513 * until new GeoBox coordinates parsing is solved */ 515 514 // if (input.lastIndexOf(cBBoxCommunStart) != -1) { -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionExporter.java
r29922 r30738 30 30 } 31 31 32 33 32 @Override 33 public Collection<Layer> getDependencies() { 34 34 return Collections.emptySet(); 35 35 } 36 36 37 38 37 @Override 38 public Component getExportPanel() { 39 39 final JPanel p = new JPanel(new GridBagLayout()); 40 40 export = new JCheckBox(); … … 46 46 p.add(GBC.glue(1,0), GBC.std().fill(GBC.HORIZONTAL)); 47 47 return p; 48 48 } 49 49 50 51 50 @Override 51 public boolean shallExport() { 52 52 return export.isSelected(); 53 53 } 54 54 55 56 57 58 55 @Override 56 public boolean requiresZip() { 57 return false; 58 } 59 59 60 61 60 @Override 61 public Element export(ExportSupport support) throws IOException { 62 62 Element layerEl = support.createElement("layer"); 63 63 layerEl.setAttribute("type", "cadastre-fr"); … … 76 76 file.appendChild(support.createTextNode(url.toString())); 77 77 return layerEl; 78 78 } 79 79 80 80 } -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CadastreSessionImporter.java
r30701 r30738 22 22 public class CadastreSessionImporter implements SessionLayerImporter{ 23 23 24 25 26 27 24 @Override 25 public Layer load(Element elem, ImportSupport support, 26 ProgressMonitor progressMonitor) throws IOException, 27 IllegalDataException { 28 28 String version = elem.getAttribute("version"); 29 29 if (!"0.1".equals(version)) { … … 41 41 fileStr = URLDecoder.decode(fileStr, "UTF-8"); 42 42 fileStr = fileStr.substring(fileStr.indexOf(":/")+2); 43 43 String filename = fileStr.substring(fileStr.lastIndexOf("/")+1,fileStr.length()); 44 44 String ext = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length()); 45 45 // create layer and load cache … … 60 60 throw new RuntimeException(e); 61 61 } 62 62 } 63 63 64 64 } -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java
r30737 r30738 43 43 private static String errorMessage; 44 44 45 45 /** 46 * Constructs a new {@code DownloadSVGBuilding}. 47 */ 46 48 public DownloadSVGBuilding(WMSLayer wmsLayer) { 47 49 super(tr("Downloading {0}", wmsLayer.getName())); … … 240 242 wmsInterface.urlConn.setRequestMethod("GET"); 241 243 wmsInterface.setCookie(); 242 InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);243 244 File file = new File(CadastrePlugin.cacheDir + "building.svg"); 244 245 String svg = new String(); 245 try { 246 try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) { 246 247 if (file.exists()) 247 248 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 } 259 259 } catch (IOException e) { 260 e.printStackTrace(System.out); 261 } 262 is.close(); 260 Main.error(e); 261 } 263 262 return svg; 264 263 } -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGTask.java
r30737 r30738 47 47 private static String errorMessage; 48 48 49 /** 50 * Constructs a new {@code DownloadSVGTask}. 51 */ 49 52 public DownloadSVGTask(WMSLayer wmsLayer) { 50 53 super(tr("Downloading {0}", wmsLayer.getName())); … … 194 197 wmsInterface.urlConn.setRequestMethod("GET"); 195 198 wmsInterface.setCookie(); 196 InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);197 199 File file = new File(CadastrePlugin.cacheDir + "boundary.svg"); 198 200 String svg = new String(); 199 try { 201 try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) { 200 202 if (file.exists()) 201 203 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 } 210 213 } 211 br.close();212 bos.close();213 214 } catch (IOException e) { 214 e.printStackTrace(System.out); 215 } 216 is.close(); 215 Main.error(e); 216 } 217 217 return svg; 218 218 } -
applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/WMSLayer.java
r30737 r30738 133 133 // if the layer is currently saving the images in the cache, wait until it's finished 134 134 if(grabThread != null) 135 135 grabThread.cancel(); 136 136 grabThread = null; 137 137 super.destroy(); -
applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanVecTile.java
r30737 r30738 23 23 24 24 public class CanVecTile { 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 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 } 320 320 } -
applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelper.java
r29854 r30738 8 8 public class CanvecHelper extends Plugin { 9 9 10 11 12 13 14 10 public CanvecHelper(PluginInformation info) { 11 super(info); 12 Main.main.menu.imagerySubMenu.add(new CanvecHelperAction(this)); 13 } 14 15 15 @Override 16 17 18 16 public void mapFrameInitialized(MapFrame old, MapFrame new1) { 17 updateLayer(); 18 } 19 19 20 21 20 private synchronized void updateLayer() { 21 } 22 22 } -
applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecHelperAction.java
r29854 r30738 5 5 6 6 public class CanvecHelperAction extends JosmAction { 7 8 9 10 11 7 private CanvecHelper parent_temp; 8 public CanvecHelperAction(CanvecHelper parent) { 9 super("CanVec Helper","layericon24",null,null,false); 10 parent_temp = parent; 11 } 12 12 @Override 13 14 15 16 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 } 18 18 } -
applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/CanvecLayer.java
r30737 r30738 1 1 package org.openstreetmap.josm.plugins.canvec_helper; 2 3 import static org.openstreetmap.josm.tools.I18n.tr; 2 4 3 5 import java.awt.Color; 4 6 import java.awt.Component; 7 import java.awt.Graphics2D; 8 import java.awt.Toolkit; 5 9 import java.awt.event.ActionEvent; 6 10 import java.awt.event.MouseEvent; 7 11 import java.awt.event.MouseListener; 8 import java.awt.Graphics2D;9 import java.awt.Toolkit;10 12 import java.io.BufferedReader; 13 import java.io.IOException; 11 14 import java.io.InputStream; 12 15 import java.io.InputStreamReader; 13 import java.io.IOException;14 16 import java.util.ArrayList; 15 17 import java.util.List; 16 18 import java.util.regex.Matcher; 17 19 import java.util.regex.Pattern; 20 18 21 import javax.swing.AbstractAction; 19 22 import javax.swing.Action; … … 22 25 import javax.swing.JMenu; 23 26 import javax.swing.JMenuItem; 27 28 import org.openstreetmap.josm.Main; 24 29 import org.openstreetmap.josm.data.Bounds; 25 30 import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor; 31 import org.openstreetmap.josm.gui.MapView; 26 32 import org.openstreetmap.josm.gui.dialogs.LayerListDialog; 27 33 import org.openstreetmap.josm.gui.dialogs.LayerListPopup; 28 34 import org.openstreetmap.josm.gui.layer.Layer; 29 import org.openstreetmap.josm.gui.MapView;30 35 import org.openstreetmap.josm.io.CachedFile; 31 import static org.openstreetmap.josm.tools.I18n.tr;32 36 33 37 // most of the layout was copied from the openstreetbugs plugin to get things started 34 38 public 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 } 230 236 } -
applications/editors/josm/plugins/canvec_helper/src/org/openstreetmap/josm/plugins/canvec_helper/SetMaxZoom.java
r29854 r30738 5 5 6 6 class SetMaxZoom extends AbstractAction { 7 8 9 10 11 12 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 } 14 14 @Override 15 16 17 15 public void actionPerformed(ActionEvent ev) { 16 parent.setMaxZoom(level); 17 } 18 18 } -
applications/editors/josm/plugins/czechaddress/src/org/openstreetmap/josm/plugins/czechaddress/parser/DatabaseParser.java
r23190 r30738 1 1 package org.openstreetmap.josm.plugins.czechaddress.parser; 2 2 3 import org.openstreetmap.josm.plugins.czechaddress.addressdatabase.*;4 3 import java.io.BufferedOutputStream; 5 4 import java.io.File; … … 9 8 import java.net.HttpURLConnection; 10 9 import java.net.URL; 10 11 11 import org.openstreetmap.josm.Main; 12 12 import org.openstreetmap.josm.plugins.czechaddress.DatabaseLoadException; 13 import org.openstreetmap.josm.plugins.czechaddress.addressdatabase.Database; 13 14 14 15 /** … … 109 110 "Požadavek na server selhal, číslo chyby: " + String.valueOf( con.getResponseCode() )); 110 111 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 } 119 120 } 120 121 bos.close();122 121 123 122 // 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 30 30 31 31 /** 32 * @author dmuecke Data import for TangoGPS file format. 32 * Data import for TangoGPS file format. 33 * @author dmuecke 33 34 */ 34 35 public class TangoGPS extends FileImporter { … … 40 41 /** 41 42 * @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. 44 44 * Read a log file from TangoGPS. These are simple text files in the 45 45 * form: <lat>,<lon>,<elevation>,<speed>,<course>,<hdop>,<datetime> … … 53 53 int failure = 0; 54 54 55 BufferedReader rd = null; 56 try { 55 try ( 57 56 InputStream source = new FileInputStream(file); 58 rd = new BufferedReader(new InputStreamReader(source)); 59 57 BufferedReader rd = new BufferedReader(new InputStreamReader(source)); 58 ) { 60 59 String line; 61 60 while ((line = rd.readLine()) != null) { … … 72 71 imported++; 73 72 } catch (NumberFormatException e) { 74 e.printStackTrace();73 Main.error(e); 75 74 } 76 75 } … … 92 91 } 93 92 showInfobox(imported,failure); 94 } finally {95 if (rd != null) {96 rd.close();97 }98 93 } 99 94 } … … 106 101 if (lineElements.length < 2) 107 102 return null; 108 return new LatLon(parseCoord(lineElements[0]), 109 parseCoord(lineElements[1])); 103 return new LatLon(parseCoord(lineElements[0]), parseCoord(lineElements[1])); 110 104 } 111 105 … … 118 112 } 119 113 } 120 121 122 114 } -
applications/editors/josm/plugins/ext_tools/src/ext_tools/ToolsInformation.java
r30737 r30738 8 8 import java.util.ArrayList; 9 9 import java.util.List; 10 11 import org.openstreetmap.josm.Main; 10 12 11 13 public class ToolsInformation { … … 20 22 21 23 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"))) { 25 26 StringBuilder sb = new StringBuilder(); 26 27 String line; … … 32 33 } 33 34 } 34 rdr.close();35 35 } 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); 38 37 } 39 38 } 40 39 41 40 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")) { 45 42 for (ExtTool tool : tools) 46 43 w.write(tool.serialize()); 47 w.close();48 44 } 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); 51 46 } 52 47 } -
applications/editors/josm/plugins/globalsat/src/org/kaintoch/gps/globalsat/dg100/Dg100Config.java
r29854 r30738 11 11 import java.nio.ByteBuffer; 12 12 import java.util.Properties; 13 14 import org.openstreetmap.josm.Main; 13 15 14 16 /** … … 107 109 } 108 110 109 public String toString() 111 @Override 112 public String toString() 110 113 { 111 114 return … … 459 462 props.setProperty(propUnk3, "" + unk3); 460 463 props.setProperty(propUnk4, "" + unk4); 461 OutputStream os = null; 462 try 463 { 464 os = new FileOutputStream(fName); 464 465 try (OutputStream os = new FileOutputStream(fName)) { 465 466 props.store(os, "dg100 config"); 466 } 467 catch (Exception ex) 468 { 469 ex.printStackTrace(); 467 } catch (Exception ex) { 468 Main.error(ex); 470 469 throw ex; 471 470 } 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 { 481 474 Properties props = new Properties(); 482 InputStream is = null; 483 try 484 { 485 is = new FileInputStream(fName); 475 476 try (InputStream is = new FileInputStream(fName)) { 486 477 props.load(is); 487 } 488 catch (Exception ex) 489 { 490 ex.printStackTrace(); 478 } catch (Exception ex) { 479 Main.error(ex);; 491 480 throw ex; 492 }493 finally494 {495 if (is != null) {is.close();}496 481 } 497 482 logFormat = Byte.parseByte(props.getProperty(propLogFormat, "2")); -
applications/editors/josm/plugins/gpxfilter/src/gpxfilter/GpxGrabber.java
r29222 r30738 23 23 private final double lat2; 24 24 private final double lon2; 25 25 26 26 private int page; 27 27 … … 31 31 this.lat2 = downloadArea.getMax().lat(); 32 32 this.lon2 = downloadArea.getMax().lon(); 33 33 34 34 page = 0; 35 35 } … … 42 42 */ 43 43 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)) { 48 46 GpxReader reader = new GpxReader(in); 49 47 reader.parse(false); 50 48 GpxData result = reader.getGpxData(); 51 in.close();52 49 result.fromServer = true; 53 50 page++; … … 70 67 return null; 71 68 throw e; 72 } } 69 } 70 } 73 71 74 72 @Override -
applications/editors/josm/plugins/imagery_offset_db/src/iodb/ImageryOffsetPlugin.java
r30737 r30738 1 1 package iodb; 2 2 3 import static org.openstreetmap.josm.tools.I18n.marktr; 4 3 5 import java.awt.event.KeyEvent; 4 import java.util.*; 6 import java.util.Collection; 7 import java.util.LinkedList; 8 5 9 import javax.swing.JMenu; 10 6 11 import org.openstreetmap.josm.Main; 7 12 import org.openstreetmap.josm.data.Version; 13 import org.openstreetmap.josm.gui.preferences.ToolbarPreferences; 8 14 import org.openstreetmap.josm.plugins.Plugin; 9 15 import org.openstreetmap.josm.plugins.PluginInformation; 10 import static org.openstreetmap.josm.tools.I18n.marktr;11 16 12 17 /** 13 18 * A plugin to request and store imagery offsets in the centralized database. 14 * 19 * 15 20 * @author Zverik 16 21 * @license WTFPL … … 19 24 private GetImageryOffsetAction getAction; 20 25 private StoreImageryOffsetAction storeAction; 21 26 22 27 /** 23 28 * Add both actions to their own menu. This creates … … 28 33 public ImageryOffsetPlugin( PluginInformation info ) { 29 34 super(info); 30 35 31 36 getAction = new GetImageryOffsetAction(); 32 37 storeAction = new StoreImageryOffsetAction(); 33 38 34 39 // before 5803 imagery menu was constantly regenerated, erasing extra items 35 40 // before 5729 it was regenerated only when the imagery list was modified (also bad) … … 43 48 // an ugly hack to add this plugin to the toolbar 44 49 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()); 46 51 if( !toolbar.contains("getoffset") ) { 47 52 toolbar.add("getoffset"); -
applications/editors/josm/plugins/imagery_offset_db/src/iodb/OffsetDialog.java
r30737 r30738 1 1 package iodb; 2 2 3 import java.awt.*; 3 import static org.openstreetmap.josm.tools.I18n.tr; 4 5 import java.awt.BasicStroke; 6 import java.awt.Color; 7 import java.awt.Component; 8 import java.awt.FlowLayout; 9 import java.awt.Graphics2D; 10 import java.awt.GridLayout; 11 import java.awt.Point; 12 import java.awt.RenderingHints; 4 13 import java.awt.event.ActionEvent; 5 14 import java.awt.event.ActionListener; … … 8 17 import java.net.HttpURLConnection; 9 18 import java.net.URL; 10 import java.util.*; 19 import java.util.ArrayList; 20 import java.util.Date; 11 21 import java.util.List; 12 import javax.swing.*; 22 23 import javax.swing.AbstractAction; 24 import javax.swing.Box; 25 import javax.swing.BoxLayout; 26 import javax.swing.JButton; 27 import javax.swing.JCheckBox; 28 import javax.swing.JComponent; 29 import javax.swing.JDialog; 30 import javax.swing.JOptionPane; 31 import javax.swing.JPanel; 32 import javax.swing.JPopupMenu; 33 import javax.swing.KeyStroke; 13 34 import javax.swing.border.CompoundBorder; 14 35 import javax.swing.border.EmptyBorder; 36 15 37 import org.openstreetmap.josm.Main; 16 38 import org.openstreetmap.josm.data.Bounds; … … 19 41 import org.openstreetmap.josm.gui.layer.ImageryLayer; 20 42 import org.openstreetmap.josm.gui.layer.MapViewPaintable; 21 import org.openstreetmap.josm.tools.*; 22 import static org.openstreetmap.josm.tools.I18n.tr; 43 import org.openstreetmap.josm.tools.ImageProvider; 44 import org.openstreetmap.josm.tools.LanguageInfo; 45 import org.openstreetmap.josm.tools.OpenBrowser; 46 import org.openstreetmap.josm.tools.Utils; 23 47 24 48 /** 25 49 * The dialog which presents a choice between imagery align options. 26 * 50 * 27 51 * @author Zverik 28 52 * @license WTFPL … … 31 55 protected static final String PREF_CALIBRATION = "iodb.show.calibration"; 32 56 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); 34 58 35 59 /** … … 45 69 46 70 /** 47 * Initialize the dialog and install listeners. 71 * Initialize the dialog and install listeners. 48 72 * @param offsets The list of offset to choose from. 49 73 */ … … 60 84 JComponent.WHEN_IN_FOCUSED_WINDOW); 61 85 } 62 86 63 87 /** 64 88 * Creates the GUI. … … 69 93 calibrationBox.setSelected(Main.pref.getBoolean(PREF_CALIBRATION, true)); 70 94 calibrationBox.addActionListener(new ActionListener() { 71 public void actionPerformed( ActionEvent e ) { 95 @Override 96 public void actionPerformed( ActionEvent e ) { 72 97 Main.pref.put(PREF_CALIBRATION, calibrationBox.isSelected()); 73 98 updateButtonPanel(); … … 77 102 deprecatedBox.setSelected(Main.pref.getBoolean(PREF_DEPRECATED, false)); 78 103 deprecatedBox.addActionListener(new ActionListener() { 79 public void actionPerformed( ActionEvent e ) { 104 @Override 105 public void actionPerformed( ActionEvent e ) { 80 106 Main.pref.put(PREF_DEPRECATED, deprecatedBox.isSelected()); 81 107 updateButtonPanel(); … … 154 180 * It does nothing, only passes the event to all displayed offset buttons. 155 181 */ 156 public void zoomChanged() { 182 @Override 183 public void zoomChanged() { 157 184 for( Component c : buttonPanel.getComponents() ) { 158 185 if( c instanceof OffsetDialogButton ) { … … 166 193 * value, but looks nice. 167 194 */ 168 public void paint( Graphics2D g, MapView mv, Bounds bbox ) { 195 @Override 196 public void paint( Graphics2D g, MapView mv, Bounds bbox ) { 169 197 if( offsets == null ) 170 198 return; … … 181 209 } 182 210 } 183 211 184 212 /** 185 213 * Display the dialog and get the return value is case of a modal frame. … … 208 236 * @see #applyOffset() 209 237 */ 210 public void actionPerformed( ActionEvent e ) { 238 @Override 239 public void actionPerformed( ActionEvent e ) { 211 240 if( e.getSource() instanceof OffsetDialogButton ) { 212 241 selectedOffset = ((OffsetDialogButton)e.getSource()).getOffset(); … … 283 312 * Remove the deprecated offset from the offsets list. Then rebuild the button panel. 284 313 */ 285 public void queryPassed() { 314 @Override 315 public void queryPassed() { 286 316 offset.setDeprecated(new Date(), JosmUserIdentityManager.getInstance().getUserName(), ""); 287 317 updateButtonPanel(); … … 299 329 } 300 330 301 public void actionPerformed( ActionEvent e ) { 331 @Override 332 public void actionPerformed( ActionEvent e ) { 302 333 String base = Main.pref.get("url.openstreetmap-wiki", "http://wiki.openstreetmap.org/wiki/"); 303 334 String lang = LanguageInfo.getWikiLanguagePrefix(); -
applications/editors/josm/plugins/imagery_offset_db/src/iodb/StoreImageryOffsetAction.java
r30737 r30738 117 117 query.append(key).append('=').append(URLEncoder.encode(params.get(key), "UTF8")); 118 118 } 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..."))); 120 120 } catch( UnsupportedEncodingException ex ) { 121 121 // WTF -
applications/editors/josm/plugins/imagerycache/src/org/openstreetmap/josm/plugins/imagerycache/OsmDBTilesLoader.java
r29769 r30738 11 11 import java.util.Map; 12 12 import java.util.Random; 13 13 14 import org.openstreetmap.gui.jmapviewer.JobDispatcher; 14 15 import org.openstreetmap.gui.jmapviewer.OsmTileLoader; … … 20 21 import org.openstreetmap.gui.jmapviewer.interfaces.TileSource; 21 22 import org.openstreetmap.gui.jmapviewer.interfaces.TileSource.TileUpdate; 23 import org.openstreetmap.josm.Main; 22 24 import org.openstreetmap.josm.data.preferences.BooleanProperty; 23 25 24 26 /** 25 * 27 * 26 28 * @author Alexei Kasatkin, based on OsmFileCacheTileLoader by @author Jan Peter Stotz, @author Stefan Zeller 27 29 */ 28 30 class OsmDBTilesLoader extends OsmTileLoader implements CachedTileLoader { 29 30 31 32 31 33 public static final long FILE_AGE_ONE_DAY = 1000 * 60 * 60 * 24; 32 34 public static final long FILE_AGE_ONE_WEEK = FILE_AGE_ONE_DAY * 7; 33 35 34 36 public static final boolean debug = new BooleanProperty("imagerycache.debug", false).get(); 35 37 36 38 TileDAOMapDB dao; 37 39 38 40 protected long maxCacheFileAge = FILE_AGE_ONE_WEEK; 39 41 protected long recheckAfter = FILE_AGE_ONE_DAY; 40 42 41 43 42 44 public OsmDBTilesLoader(TileLoaderListener smap, File cacheFolder) { 43 45 super(smap); … … 45 47 dao.setCacheFolder(cacheFolder); 46 48 } 47 49 48 50 @Override 49 51 public TileJob createTileLoaderJob(final Tile tile) { … … 60 62 dao.cleanStorage(source.getName()); 61 63 } 62 64 63 65 protected class DatabaseLoadJob implements TileJob { 64 66 65 67 private final Tile tile; 66 68 File tileCacheDir; 67 69 68 70 /** 69 * Stores the tile loaded from database, null if nothing found. 71 * Stores the tile loaded from database, null if nothing found. 70 72 */ 71 73 DBTile dbTile = null; 72 74 long fileAge = 0; 73 75 74 76 long id; 75 77 String sourceName; 76 78 77 79 public DatabaseLoadJob(Tile tile) { 78 80 this.tile = tile; … … 112 114 113 115 /** 114 * Loads tile from database. 116 * Loads tile from database. 115 117 * There can be dbTile != null but the tile is outdated and reload is still needed 116 118 * @return true if no loading from server is needed. … … 120 122 try { 121 123 dbTile = dao.getById(sourceName, id); 122 124 123 125 if (dbTile == null) return false; 124 125 loadMetadata(); 126 127 loadMetadata(); 126 128 if (debug) System.out.println(id+": found in cache, metadata ="+dbTile.metaData); 127 129 … … 149 151 } 150 152 } 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); 153 155 try { 154 156 if (bin != null) { … … 161 163 return false; // tile is not because of some error (corrupted database, etc.) 162 164 } 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; 166 168 } 167 169 } … … 170 172 return System.currentTimeMillis() - maxCacheFileAge + recheckAfter; 171 173 } 172 174 173 175 private void loadOrUpdateTileFromServer() { 174 176 175 177 try { 176 178 URLConnection urlConn = loadTileFromOsm(tile); … … 195 197 dbTile = new DBTile(); 196 198 } 197 199 198 200 if (tileUpdate == TileSource.TileUpdate.ETag || tileUpdate == TileSource.TileUpdate.IfNoneMatch) { 199 201 String fileETag = tile.getValue("etag"); … … 224 226 loadTileMetadata(tile, urlConn); 225 227 dbTile.metaData = tile.getMetadata(); 226 228 227 229 if ("no-tile".equals(tile.getValue("tile-info"))) 228 230 { … … 248 250 } 249 251 } 250 252 251 253 } catch (Exception e) { 252 254 tile.setError(e.getMessage()); … … 261 263 } 262 264 } 263 264 265 266 265 267 protected byte[] loadTileInBuffer(URLConnection urlConn) throws IOException { 266 268 InputStream input = urlConn.getInputStream(); … … 292 294 * </ul> 293 295 * 294 * @param fileAge time of the 296 * @param fileAge time of the 295 297 * @return <code>true</code> if the tile on the server is newer than the 296 298 * file -
applications/editors/josm/plugins/mapdust/src/org/openstreetmap/josm/plugins/mapdust/util/http/HttpConnector.java
r25591 r30738 38 38 import java.net.URLEncoder; 39 39 import java.util.Map; 40 40 41 import org.openstreetmap.josm.plugins.mapdust.util.retry.RetryAgent; 41 42 import org.openstreetmap.josm.plugins.mapdust.util.retry.RetrySetup; … … 160 161 /* 3: write content */ 161 162 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 } 167 167 } 168 168 -
applications/editors/josm/plugins/native-password-manager/src/org/netbeans/modules/keyring/kde/KWalletProvider.java
r26335 r30738 49 49 import java.util.logging.Level; 50 50 import java.util.logging.Logger; 51 51 52 import org.netbeans.spi.keyring.KeyringProvider; 52 53 … … 69 70 } 70 71 CommandResult result = runCommand("isEnabled"); 71 if(new String(result.retVal).equals("true")) { 72 if(new String(result.retVal).equals("true")) { 72 73 return updateHandler(); 73 } 74 } 74 75 return false; 75 76 }; … … 121 122 } 122 123 handler = new String(handler).equals("")? "0".toCharArray() : handler; 123 CommandResult result = runCommand("isOpen",handler); 124 CommandResult result = runCommand("isOpen",handler); 124 125 if(new String(result.retVal).equals("true")){ 125 126 return true; 126 127 } 127 128 char[] localWallet = defaultLocalWallet; 128 result = runCommand("localWallet"); 129 if(result.exitCode == 0) { 129 result = runCommand("localWallet"); 130 if(result.exitCode == 0) { 130 131 localWallet = result.retVal; 131 132 } 132 133 if(new String(localWallet).contains(".service")) { 133 134 if(new String(localWallet).contains(".service")) { 134 135 //Temporary workaround for the bug in kdelibs/kdeui/util/kwallet.cpp 135 136 //The bug was fixed http://svn.reviewboard.kde.org/r/5885/diff/ … … 138 139 } 139 140 result = runCommand("open", localWallet , "0".toCharArray(), getApplicationName(true)); 140 if(result.exitCode == 2) { 141 if(result.exitCode == 2) { 141 142 warning("time out happened while accessing KWallet"); 142 143 //don't try to open KWallet anymore until bug https://bugs.kde.org/show_bug.cgi?id=259229 is fixed 143 144 timeoutHappened = true; 144 145 return false; 145 } 146 } 146 147 if(result.exitCode != 0 || new String(result.retVal).equals("-1")) { 147 148 warning("failed to access KWallet"); 148 149 return false; 149 } 150 } 150 151 handler = result.retVal; 151 152 return true; 152 153 } 153 154 154 155 155 156 156 157 private CommandResult runCommand(String command,char[]... commandArgs) { … … 174 175 } 175 176 Process pr = rt.exec(argv); 176 177 BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));178 179 177 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); 183 185 } 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); 192 194 } 193 errVal = errVal.concat(line); 194 } 195 input.close(); 195 } 196 196 197 197 exitCode = pr.waitFor(); … … 199 199 logger.log(Level.FINE, "application exit with code {0} for commandString: {1}; errVal: {2}", 200 200 new Object[]{exitCode, Arrays.toString(argv), errVal}); 201 } 201 } 202 202 } catch (InterruptedException ex) { 203 203 logger.log(Level.FINE, … … 210 210 } 211 211 return new CommandResult(exitCode, retVal.trim().toCharArray(), errVal.trim()); 212 } 212 } 213 213 214 214 private char[] getApplicationName(){ … … 222 222 private void warning(String descr) { 223 223 logger.log(Level.WARNING, "Something went wrong: {0}", descr); 224 } 225 224 } 225 226 226 private class CommandResult { 227 227 private int exitCode; 228 228 private char[] retVal; 229 private String errVal;230 229 231 230 public CommandResult(int exitCode, char[] retVal, String errVal) { 232 231 this.exitCode = exitCode; 233 232 this.retVal = retVal; 234 this.errVal = errVal; 235 } 233 } 236 234 } 237 235 -
applications/editors/josm/plugins/opendata/includes/org/apache/poi/hssf/record/formula/function/FunctionMetadataReader.java
r30737 r30738 22 22 import java.io.InputStream; 23 23 import java.io.InputStreamReader; 24 import java.io.UnsupportedEncodingException;25 24 import java.util.Arrays; 26 25 import java.util.HashSet; … … 32 31 /** 33 32 * Converts the text meta-data file into a <tt>FunctionMetadataRegistry</tt> 34 * 33 * 35 34 * @author Josh Micich 36 35 */ … … 38 37 39 38 private static final String METADATA_FILE_NAME = "functionMetadata.txt"; 40 39 41 40 /** plain ASCII text metadata file uses three dots for ellipsis */ 42 41 private static final String ELLIPSIS = "..."; … … 59 58 } 60 59 61 BufferedReader br;62 try {63 br = new BufferedReader(new InputStreamReader(is,"UTF-8"));64 } catch(UnsupportedEncodingException e) {65 throw new RuntimeException(e);66 }67 60 FunctionDataBuilder fdb = new FunctionDataBuilder(400); 68 61 69 try { 62 try (BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"))) { 70 63 while (true) { 71 64 String line = br.readLine(); … … 82 75 processLine(fdb, line); 83 76 } 84 br.close();85 77 } catch (IOException e) { 86 78 throw new RuntimeException(e); … … 107 99 validateFunctionName(functionName); 108 100 // TODO - make POI use isVolatile 109 fdb.add(functionIndex, functionName, minParams, maxParams, 101 fdb.add(functionIndex, functionName, minParams, maxParams, 110 102 returnClassCode, parameterClassCodes, hasNote); 111 103 } 112 104 113 105 114 106 private static byte parseReturnTypeCode(String code) { … … 164 156 165 157 /** 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 167 159 * left behind 168 160 */ … … 182 174 return; 183 175 } 184 throw new RuntimeException("Invalid function name '" + functionName 176 throw new RuntimeException("Invalid function name '" + functionName 185 177 + "' (is footnote number incorrectly appended)"); 186 178 } -
applications/editors/josm/plugins/opendata/modules/fr.datagouvfr/src/org/openstreetmap/josm/plugins/opendata/modules/fr/datagouvfr/datasets/hydrologie/EauxDeSurfaceHandler.java
r30731 r30738 14 14 import java.util.regex.Pattern; 15 15 16 import org.openstreetmap.josm.Main; 16 17 import org.openstreetmap.josm.data.osm.DataSet; 17 18 import org.openstreetmap.josm.plugins.opendata.core.io.archive.DefaultArchiveHandler; … … 23 24 private static final String ZIP_PATTERN = "FR(.*)_SW"; 24 25 private static final String SHP_PATTERN = "FR_(.*)_SWB_.W_20......"; 25 26 26 27 private static final class WaterAgency { 27 28 public final String code; … … 34 35 } 35 36 } 36 37 37 38 private static final WaterAgency[] waterAgencies = new WaterAgency[]{ 38 39 new WaterAgency("A", "Escaut Somme", "Escaut-Somme-30381967"), … … 49 50 new WaterAgency("L", "La Réunion", "Réunion-30381991"), 50 51 }; 51 52 52 53 public EauxDeSurfaceHandler() { 53 54 setName("Eaux de surface"); 54 55 setArchiveHandler(new InternalZipHandler()); 55 56 } 56 57 57 58 @Override 58 59 public boolean acceptsFilename(String filename) { … … 63 64 return result; 64 65 } 65 66 66 67 @Override 67 68 public boolean acceptsUrl(String url) { … … 91 92 // TODO Auto-generated method stub 92 93 } 93 94 94 95 @Override 95 96 public List<Pair<String, URL>> getDataURLs() { … … 106 107 107 108 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")); 109 111 } 110 112 111 113 private class InternalZipHandler extends DefaultArchiveHandler { 112 114 @Override 113 115 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 ;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))) { 117 119 String line = reader.readLine(); 118 reader.close();119 120 if (!line.contains("\"")) { 120 121 for (String term : new String[]{"GCS_ETRS_1989", "D_ETRS_1989", "GRS_1980", "Greenwich", "Degree"}) { 121 122 line = line.replace(term, "\""+term+"\""); 122 123 } 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 } 126 127 } 127 128 } catch (Exception e) { 128 e.printStackTrace();129 Main.error(e); 129 130 } 130 131 } -
applications/editors/josm/plugins/opendata/src/org/geotools/data/shapefile/files/TabFiles.java
r30731 r30738 717 717 * if a problem occurred opening the stream. 718 718 */ 719 @SuppressWarnings("resource") 719 720 @Override 720 721 public OutputStream getOutputStream(ShpFileType type, -
applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/NeptuneReader.java
r30723 r30738 4 4 import java.io.File; 5 5 import java.io.FileInputStream; 6 import java.io.FileNotFoundException;7 6 import java.io.IOException; 8 7 import java.io.InputStream; … … 54 53 /** 55 54 * 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 57 56 */ 58 57 public class NeptuneReader extends AbstractReader implements FrenchConstants { … … 81 80 schemas.add(NeptuneReader.class.getResource(NEPTUNE_XSD)); 82 81 } 83 82 84 83 private ChouettePTNetworkType root; 85 84 86 85 private final Map<String, OsmPrimitive> tridentObjects = new HashMap<>(); 87 86 88 87 public static final boolean acceptsXmlNeptuneFile(File file) { 89 88 return acceptsXmlNeptuneFile(file, null); … … 91 90 92 91 public static final boolean acceptsXmlNeptuneFile(File file, URL schemaURL) { 93 92 94 93 if (schemaURL == null) { 95 94 schemaURL = schemas.get(0); 96 95 } 97 98 try { 99 FileInputStream in = new FileInputStream(file); 96 97 try (FileInputStream in = new FileInputStream(file)) { 100 98 Source xmlFile = new StreamSource(in); 101 99 try { … … 112 110 Main.error(xmlFile.getSystemId() + " is NOT valid"); 113 111 Main.error("Reason: " + e.getLocalizedMessage()); 114 } finally {115 try {116 in.close();117 } catch (IOException e) {118 // Ignore exception119 }120 112 } 121 } catch ( FileNotFoundException e) {113 } catch (IOException e) { 122 114 Main.error(e.getMessage()); 123 115 } 124 116 125 117 return false; 126 118 } 127 119 128 120 public static DataSet parseDataSet(InputStream in, AbstractDataSetHandler handler, ProgressMonitor instance) throws JAXBException { 129 121 return new NeptuneReader().parse(in, instance); … … 138 130 return doc.getValue(); 139 131 } 140 132 141 133 private final void linkTridentObjectToOsmPrimitive(TridentObjectType object, OsmPrimitive p) { 142 134 p.put("ref:neptune", object.getObjectId()); … … 151 143 return n; 152 144 } 153 145 154 146 private Node createPlatform(StopPointType stop) { 155 147 Node n = createNode(createLatLon(stop)); … … 181 173 return r; 182 174 } 183 175 184 176 protected Relation createNetwork(PTNetworkType network) { 185 177 Relation r = createRelation(OSM_NETWORK); … … 188 180 return r; 189 181 } 190 182 191 183 protected Relation createRouteMaster(LineType line) { 192 184 Relation r = createPtRelation(OSM_ROUTE_MASTER, line); … … 219 211 return r; 220 212 } 221 213 222 214 protected Relation createStopArea(StopAreaType sa) { 223 215 Relation r = createPtRelation(OSM_STOP_AREA, sa); … … 225 217 return r; 226 218 } 227 219 228 220 protected LatLon createLatLon(PointType point) { 229 221 return new LatLon(point.getLatitude().doubleValue(), point.getLongitude().doubleValue()); 230 222 } 231 223 232 224 protected final <T extends TridentObjectType> T findTridentObject(List<T> list, String id) { 233 225 for (T object : list) { … … 238 230 return null; 239 231 } 240 232 241 233 protected StopPoint findStopPoint(String id) { 242 234 return findTridentObject(root.getChouetteLineDescription().getStopPoint(), id); … … 311 303 } 312 304 } 313 305 314 306 } else if (childId.contains("StopPoint")) { 315 307 StopPoint child = findStopPoint(childId); … … 352 344 addStopToRoute(route, start); 353 345 } 354 346 355 347 if (end == null) { 356 348 System.err.println("Cannot find end StopPoint: "+ptlink.getEndOfLink()); … … 361 353 } 362 354 } 363 355 364 356 return ds; 365 357 } 366 358 367 359 private static final boolean addStopToRoute(Relation route, OsmPrimitive stop) { 368 360 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 33 33 34 34 private final IInArchive archive = new Handler(); 35 35 36 36 public SevenZipReader(InputStream in, AbstractDataSetHandler handler, boolean promptUser) throws IOException { 37 37 super(handler, handler != null ? handler.getArchiveHandler() : null, promptUser); … … 41 41 Utils.copyStream(in, out); 42 42 } 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); 50 51 } 51 throw new IOException(message);52 52 } 53 53 } 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) 56 56 throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException { 57 57 return new SevenZipReader(in, handler, promptUser).parseDoc(instance); 58 58 } 59 59 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) 61 61 throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException { 62 62 return new SevenZipReader(in, handler, promptUser).parseDocs(instance); … … 71 71 archive.Extract(null, -1, IInArchive.NExtract_NAskMode_kExtract, new ExtractCallback(archive, temp, candidates)); 72 72 } 73 73 74 74 private class ExtractCallback extends ArchiveExtractCallback { 75 75 private final List<File> candidates; 76 76 77 77 public ExtractCallback(IInArchive archive, File tempDir, List<File> candidates) { 78 78 Init(archive); … … 81 81 } 82 82 83 @Override 83 @Override 84 84 public int GetStream(int index, OutputStream[] outStream, int askExtractMode) throws IOException { 85 85 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 26 26 27 27 private final ZipInputStream zis; 28 28 29 29 private ZipEntry entry; 30 30 31 31 public ZipReader(InputStream in, AbstractDataSetHandler handler, boolean promptUser) { 32 32 super(handler, handler != null ? handler.getArchiveHandler() : null, promptUser); … … 34 34 } 35 35 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) 37 37 throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException { 38 38 return new ZipReader(in, handler, promptUser).parseDoc(instance); 39 39 } 40 40 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) 42 42 throws IOException, XMLStreamException, FactoryConfigurationError, JAXBException { 43 43 return new ZipReader(in, handler, promptUser).parseDocs(instance); 44 44 } 45 45 46 @Override 46 47 protected void extractArchive(final File temp, final List<File> candidates) throws IOException, FileNotFoundException { 47 48 while ((entry = zis.getNextEntry()) != null) { … … 58 59 } 59 60 if (!entry.isDirectory()) { 60 if (!file.createNewFile()) { 61 if (!file.createNewFile()) { 61 62 throw new IOException("Could not create temp file: " + file.getAbsolutePath()); 62 63 } 63 64 // 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 } 69 71 } 70 fos.close();71 72 // Allow handler to perform specific treatments (for example, fix invalid .prj files) 72 73 if (archiveHandler != null) { -
applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/io/tabular/CsvImporter.java
r30723 r30738 18 18 19 19 public class CsvImporter extends AbstractImporter { 20 20 21 21 public static final ExtensionFileFilter CSV_FILE_FILTER = new ExtensionFileFilter( 22 22 OdConstants.CSV_EXT, OdConstants.CSV_EXT, tr("CSV files") + " (*."+OdConstants.CSV_EXT+")"); 23 23 24 24 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 26 26 public CsvImporter() { 27 27 super(CSV_FILE_FILTER); … … 46 46 boolean result = false; 47 47 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); 56 51 } catch (IOException e) { 57 52 // Ignore exceptions -
applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ModuleInformation.java
r30731 r30738 73 73 this.name = name; 74 74 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 ) { 80 79 Manifest manifest = jar.getManifest(); 81 80 if (manifest == null) … … 85 84 } catch (IOException e) { 86 85 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 }98 86 } 99 87 } -
applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/modules/ReadRemoteModuleInformationTask.java
r30563 r30738 25 25 import java.util.List; 26 26 27 import org.openstreetmap.josm.Main; 27 28 import org.openstreetmap.josm.data.Version; 28 29 import org.openstreetmap.josm.gui.PleaseWaitRunnable; … … 246 247 */ 247 248 protected void cacheModuleList(String site, String list) { 248 PrintWriter writer = null;249 249 try { 250 250 File moduleDir = OdPlugin.getInstance().getModulesDirectory(); 251 251 if (!moduleDir.exists()) { 252 252 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)); 254 255 } 255 256 } 256 257 File cacheFile = createSiteCacheFile(moduleDir, site, CacheType.PLUGIN_LIST); 257 258 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 } 260 262 } catch (IOException e) { 261 263 // 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); 268 265 } 269 266 } … … 300 297 File [] f = new File(location).listFiles( 301 298 new FilenameFilter() { 299 @Override 302 300 public boolean accept(File dir, String name) { 303 301 return name.matches("^([0-9]+-)?site.*\\.txt$") || -
applications/editors/josm/plugins/opendata/src/org/openstreetmap/josm/plugins/opendata/core/util/NamesFrUtils.java
r30723 r30738 11 11 12 12 import org.apache.commons.lang3.text.WordUtils; 13 import org.openstreetmap.josm.Main; 13 14 import org.openstreetmap.josm.data.osm.OsmPrimitive; 14 15 import org.openstreetmap.josm.plugins.opendata.core.OdConstants; … … 16 17 17 18 public abstract class NamesFrUtils { 18 19 19 20 private static Map<String, String> dictionary = initDictionary(); 20 21 … … 29 30 return result; 30 31 } 31 32 32 33 private static Map<String, String> initDictionary() { 33 34 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))) { 37 37 String line = reader.readLine(); // Skip first line 38 38 while ((line = reader.readLine()) != null) { … … 40 40 result.put(tab[0].replace("\"", ""), tab[1].replace("\"", "")); 41 41 } 42 reader.close();43 42 } catch (IOException e) { 44 e.printStackTrace();43 Main.error(e); 45 44 } 46 45 return result; … … 170 169 if (value != null) { 171 170 value = WordUtils.capitalizeFully(value); 172 // Cas particuliers 171 // Cas particuliers 173 172 if (value.equals("Boulingrin")) { // square Boulingrin, mal formé 174 173 value = "Sq Boulingrin"; -
applications/editors/josm/plugins/opendata/util/opendata/ModuleListGenerator.java
r30340 r30738 15 15 import java.util.zip.ZipOutputStream; 16 16 17 import org.openstreetmap.josm.Main; 18 17 19 public class ModuleListGenerator { 18 20 … … 26 28 baseDir = args[0]; 27 29 } 28 try {30 try ( 29 31 BufferedWriter list = new BufferedWriter(new FileWriter(baseDir+"modules.txt")); 30 32 ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(baseDir+"modules-icons.zip")); 33 ) { 31 34 for (File file : new File(baseDir+"dist").listFiles(new FilenameFilter() { 32 35 @Override … … 37 40 try { 38 41 String filename = file.getName(); 39 System.out.println("Processing "+filename);42 Main.info("Processing "+filename); 40 43 list.write(filename+";"+url+filename); list.newLine(); 41 44 Manifest mf = new JarFile(file).getManifest(); … … 77 80 } 78 81 } catch (IOException e) { 79 System.err.println("Cannot load Image-Icon: "+value.toString());82 Main.error("Cannot load Image-Icon: "+value.toString()); 80 83 } finally { 81 84 zip.closeEntry(); … … 84 87 } 85 88 } 86 89 87 90 } catch (IOException e) { 88 e.printStackTrace();91 Main.error(e); 89 92 } 90 93 } 91 System.out.println("Done");92 zip.close();93 list.close();94 94 } catch (IOException e) { 95 e.printStackTrace();95 Main.error(e); 96 96 } 97 97 } -
applications/editors/josm/plugins/osmarender/src/org/openstreetmap/josm/plugins/osmarender/OsmarenderPlugin.java
r30737 r30738 54 54 55 55 @Override 56 56 public void actionPerformed(ActionEvent e) { 57 57 DataSet ds = Main.main.getCurrentDataSet(); 58 58 if (ds == null) { 59 59 return; 60 60 } 61 61 62 62 // get all stuff visible on screen 63 63 LatLon bottomLeft = Main.map.mapView.getLatLon(0,Main.map.mapView.getHeight()); … … 67 67 try { 68 68 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 } 73 73 74 74 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")) { 76 77 // 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");79 78 w.header(); 80 79 … … 116 115 117 116 // get the exec line 118 String argument; 117 String argument; 119 118 if (Main.platform instanceof PlatformHookWindows) 120 119 argument = "file:///"+getPluginDir().replace('\\','/').replace(" ","%20")+File.separator+"generated.xml\""; … … 198 197 "maxlon=\"" + b.getMax().lon() + "\" " + "/>"; 199 198 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 } 223 220 } 224 221 } -
applications/editors/josm/plugins/photo_geotagging/src/org/openstreetmap/josm/plugins/photo_geotagging/ExifGPSTagger.java
r28398 r30738 8 8 import java.io.FileOutputStream; 9 9 import java.io.IOException; 10 import java.io.OutputStream;11 10 import java.text.DecimalFormat; 12 11 import java.util.Calendar; … … 49 48 } 50 49 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; 57 53 58 59 60 61 54 IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile); 55 JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; 56 if (null != jpegMetadata) { 57 TiffImageMetadata exif = jpegMetadata.getExif(); 62 58 63 if (null != exif) { 64 outputSet = exif.getOutputSet(); 65 } 59 if (null != exif) { 60 outputSet = exif.getOutputSet(); 66 61 } 62 } 67 63 68 69 70 64 if (null == outputSet) { 65 outputSet = new TiffOutputSet(); 66 } 71 67 72 68 Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); 73 69 74 70 calendar.setTimeInMillis(gpsTime); 75 71 76 77 78 79 80 81 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); 82 78 83 84 85 79 DecimalFormat yearFormatter = new DecimalFormat("0000"); 80 DecimalFormat monthFormatter = new DecimalFormat("00"); 81 DecimalFormat dayFormatter = new DecimalFormat("00"); 86 82 87 88 89 90 91 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); 92 88 93 94 95 96 97 98 99 100 101 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); 102 98 103 104 105 106 107 108 109 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); 110 106 111 107 SanselanFixes.setGPSInDegrees(outputSet, lon, lat); 112 108 113 114 115 116 117 118 119 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); 120 116 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); 144 127 } 145 128 } -
applications/editors/josm/plugins/piclayer/src/org/openstreetmap/josm/plugins/piclayer/layer/PicLayerFromFile.java
r30436 r30738 74 74 75 75 if (isZip) { 76 ZipFile zipFile = null; 77 try 78 { 79 zipFile = new ZipFile(m_file); 76 try (ZipFile zipFile = new ZipFile(m_file)) { 80 77 ZipEntry imgEntry = null; 81 78 Enumeration<? extends ZipEntry> entries = zipFile.entries(); … … 103 100 System.err.println(tr("Warning: failed to handle zip file ''{0}''. Exception was: {1}", m_file.getName(), e.toString())); 104 101 return null; 105 } finally {106 if (zipFile != null) {107 try {108 zipFile.close();109 } catch (IOException ex) {110 }111 }112 102 } 113 103 } else { … … 149 139 150 140 if (isZip) { 151 ZipFile zipFile = null; 152 try 153 { 154 zipFile = new ZipFile(m_file); 141 try (ZipFile zipFile = new ZipFile(m_file)) { 155 142 String calFileStr = imgNameInZip + CalibrationFileFilter.EXTENSION; 156 143 ZipEntry calEntry = zipFile.getEntry(calFileStr); … … 183 170 } 184 171 } 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())); 186 173 return; 187 } finally {188 if (zipFile != null) {189 try {190 zipFile.close();191 } catch (IOException ex) {192 }193 }194 174 } 195 175 } else { -
applications/editors/josm/plugins/poly/src/poly/PolyExporter.java
r30737 r30738 25 25 /** 26 26 * Writes poly files. 27 * 27 * 28 28 * @author zverik 29 29 */ … … 37 37 public void exportData( File file, Layer layer ) throws IOException { 38 38 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"))) { 41 40 DataSet ds = ((OsmDataLayer)layer).data; 42 41 Map<Way, Boolean> ways = new TreeMap<>(); … … 71 70 writer.write("END"); 72 71 writer.newLine(); 73 } finally {74 writer.close();75 72 } 76 73 } -
applications/editors/josm/plugins/poly/src/poly/PolyImporter.java
r30737 r30738 1 1 package poly; 2 3 import static org.openstreetmap.josm.tools.I18n.tr; 2 4 3 5 import java.io.BufferedReader; … … 7 9 import java.util.ArrayList; 8 10 import java.util.List; 11 9 12 import javax.swing.JOptionPane; 13 10 14 import org.openstreetmap.josm.Main; 11 15 import org.openstreetmap.josm.data.coor.LatLon; 12 13 import static org.openstreetmap.josm.tools.I18n.tr;14 16 import org.openstreetmap.josm.data.osm.DataSet; 15 17 import org.openstreetmap.josm.data.osm.Node; … … 19 21 import org.openstreetmap.josm.gui.progress.NullProgressMonitor; 20 22 import org.openstreetmap.josm.gui.progress.ProgressMonitor; 23 import org.openstreetmap.josm.io.CachedFile; 21 24 import org.openstreetmap.josm.io.IllegalDataException; 22 import org.openstreetmap.josm.io.CachedFile;23 25 import org.openstreetmap.josm.io.OsmImporter; 24 26 import org.openstreetmap.josm.tools.CheckParameterUtil; … … 44 46 progressMonitor = NullProgressMonitor.INSTANCE; 45 47 CheckParameterUtil.ensureParameterNotNull(in, "in"); 46 BufferedReader reader = null; 47 48 try { 48 49 try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF8"))) { 49 50 progressMonitor.beginTask(tr("Reading polygon filter file..."), 2); 50 51 progressMonitor.indeterminateSubTask(tr("Reading polygon filter file...")); 51 reader = new BufferedReader(new InputStreamReader(in, "UTF8"));52 52 List<Area> areas = loadPolygon(reader); 53 53 progressMonitor.worked(1); 54 54 55 55 progressMonitor.indeterminateSubTask(tr("Preparing data set...")); 56 56 DataSet ds = constructDataSet(areas); … … 60 60 throw new IllegalDataException(tr("Error reading poly file: {0}", e.getMessage()), e); 61 61 } finally { 62 try {63 if( reader != null )64 reader.close();65 } catch( IOException e ) { }66 62 progressMonitor.finishTask(); 67 63 } 68 64 } 69 65 70 66 private List<Area> loadPolygon( BufferedReader reader ) throws IllegalDataException, IOException { 71 67 String name = reader.readLine(); … … 145 141 DataSet ds = new DataSet(); 146 142 ds.setUploadDiscouraged(true); 147 143 148 144 boolean foundInner = false; 149 145 for( Area area : areas ) { -
applications/editors/josm/plugins/proj4j/src/org/openstreetmap/josm/plugins/proj4j/Proj4JProjectionChoice.java
r30737 r30738 64 64 sorter = new TableRowSorter<>(model); 65 65 } 66 66 67 67 @Override 68 68 public String getId() { … … 74 74 return new Proj4JPanel(actionListener); 75 75 } 76 76 77 77 protected class Proj4JPanel extends JPanel { 78 78 79 79 public Proj4JPanel(ActionListener actionListener) { 80 80 GridBagConstraints c = new GridBagConstraints(); … … 94 94 new DocumentListener() { 95 95 96 @Override 96 97 public void insertUpdate(DocumentEvent e) { 97 98 newFilter(); 98 99 } 99 100 101 @Override 100 102 public void removeUpdate(DocumentEvent e) { 101 103 newFilter(); 102 104 } 103 105 106 @Override 104 107 public void changedUpdate(DocumentEvent e) { 105 108 newFilter(); … … 213 216 } 214 217 218 @Override 215 219 public void valueChanged(ListSelectionEvent e) { 216 220 updateSelectedCode(); … … 258 262 public CRSTableModel() throws java.io.IOException { 259 263 // 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 } 268 274 } 269 275 } 270 fh.close();271 276 } 272 277 -
applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelation.java
r30737 r30738 150 150 } 151 151 } else if( element.getType() == OsmPrimitiveType.RELATION ) { 152 153 152 Color oldColor = g.getColor(); 153 g.setColor(Color.magenta); 154 154 drawRelations(g, mv, bbox, (Relation)element); 155 155 g.setColor(oldColor); -
applications/editors/josm/plugins/reltoolbox/src/relcontext/ChosenRelationListener.java
r25649 r30738 9 9 */ 10 10 public interface ChosenRelationListener { 11 11 void chosenRelationChanged( Relation oldRelation, Relation newRelation ); 12 12 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/ExtraNameFormatHook.java
r26802 r30738 14 14 15 15 public String checkRelationTypeName( IRelation relation, String defaultName ) { 16 16 return null; 17 17 } 18 18 19 19 public String checkFormat( INode node, String defaultName ) { 20 20 return null; 21 21 } 22 22 23 23 public String checkFormat( IWay way, String defaultName ) { 24 25 26 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; 27 27 } 28 28 29 29 public String checkFormat( IRelation relation, String defaultName ) { 30 31 32 33 34 35 36 37 38 39 40 41 42 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; 43 43 } 44 44 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextDialog.java
r30737 r30738 97 97 /** 98 98 * The new, advanced relation editing panel. 99 * 99 * 100 100 * @author Zverik 101 101 */ … … 103 103 104 104 public final static String PREF_PREFIX = "reltoolbox"; 105 105 106 106 private final DefaultTableModel relationsData; 107 107 private ChosenRelation chosenRelation; … … 142 142 roleBox.addMouseListener(relationMouseAdapter); 143 143 roleBox.addItemListener(new ItemListener() { 144 @Override 144 145 public void itemStateChanged( ItemEvent e ) { 145 146 if( e.getStateChange() == ItemEvent.DESELECTED ) return; … … 174 175 175 176 roleBox.addPropertyChangeListener("enabled", new PropertyChangeListener() { 177 @Override 176 178 public void propertyChange( PropertyChangeEvent evt ) { 177 179 boolean showRoleBox = roleBox.isEnabled(); … … 182 184 183 185 sortAndFixAction.addPropertyChangeListener(new PropertyChangeListener() { 186 @Override 184 187 public void propertyChange( PropertyChangeEvent evt ) { 185 188 sortAndFixButton.setVisible(sortAndFixAction.isEnabled()); … … 189 192 190 193 downloadChosenRelationAction.addPropertyChangeListener(new PropertyChangeListener() { 194 @Override 191 195 public void propertyChange( PropertyChangeEvent evt ) { 192 196 downloadButton.setVisible(downloadChosenRelationAction.isEnabled()); … … 304 308 columns.getColumn(0).setPreferredWidth(220); 305 309 relationsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { 310 @Override 306 311 public void valueChanged( ListSelectionEvent e ) { 307 312 int selectedRow = relationsTable.getSelectedRow(); … … 339 344 } 340 345 346 @Override 341 347 public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) { 342 348 if( chosenRelationPanel != null && Main.pref.getBoolean(PREF_PREFIX + ".hidetopline", false) ) … … 348 354 } 349 355 356 @Override 350 357 public void selectionChanged( Collection<? extends OsmPrimitive> newSelection ) { 351 358 if( !isVisible() || relationsData == null ) … … 397 404 } 398 405 406 @Override 399 407 public void editLayerChanged( OsmDataLayer oldLayer, OsmDataLayer newLayer ) { 400 408 updateSelection(); … … 410 418 super.destroy(); 411 419 } 412 420 413 421 private static final String POSSIBLE_ROLES_FILE = "relcontext/possible_roles.txt"; 414 422 private static final Map<String, List<String>> possibleRoles = loadRoles(); … … 416 424 private static Map<String, List<String>> loadRoles() { 417 425 Map<String, List<String>> result = new HashMap<>(); 418 try {419 ClassLoader classLoader = RelContextDialog.class.getClassLoader();420 finalInputStream possibleRolesStream = classLoader.getResourceAsStream(POSSIBLE_ROLES_FILE);426 ClassLoader classLoader = RelContextDialog.class.getClassLoader(); 427 try ( 428 InputStream possibleRolesStream = classLoader.getResourceAsStream(POSSIBLE_ROLES_FILE); 421 429 BufferedReader r = new BufferedReader(new InputStreamReader(possibleRolesStream)); 430 ) { 422 431 while( r.ready() ) { 423 432 String line = r.readLine(); … … 431 440 } 432 441 } 433 r.close();434 442 } 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); 437 445 } 438 446 return result; … … 466 474 467 475 role.getEditor().addActionListener(new ActionListener() { 476 @Override 468 477 public void actionPerformed( ActionEvent e ) { 469 478 dlg.setVisible(false); … … 589 598 } 590 599 600 @Override 591 601 public void actionPerformed( ActionEvent e ) { 592 602 String property = e.getActionCommand(); … … 609 619 } 610 620 621 @Override 611 622 public void actionPerformed( ActionEvent e ) { 612 623 if( roleBoxModel.membersRole != null ) { … … 617 628 } 618 629 630 @Override 619 631 public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) { 620 632 setEnabled(newRelation != null); 621 633 } 622 634 } 623 635 624 636 private class RoleComboBoxModel extends AbstractListModel<String> implements ComboBoxModel<String> { 625 637 private List<String> roles = new ArrayList<>(); … … 704 716 } 705 717 718 @Override 706 719 public int getSize() { 707 720 return roles.size(); 708 721 } 709 722 723 @Override 710 724 public String getElementAt( int index ) { 711 725 return getRole(index); … … 716 730 } 717 731 732 @Override 718 733 public void setSelectedItem( Object anItem ) { 719 734 int newIndex = anItem == null ? -1 : roles.indexOf(anItem); … … 724 739 } 725 740 741 @Override 726 742 public Object getSelectedItem() { 727 743 return selectedIndex < 0 || selectedIndex >= getSize() ? null : getRole(selectedIndex); -
applications/editors/josm/plugins/reltoolbox/src/relcontext/RelContextPlugin.java
r29535 r30738 11 11 public RelContextPlugin( PluginInformation info ) { 12 12 super(info); 13 13 DefaultNameFormatter.registerFormatHook(new ExtraNameFormatHook()); 14 14 } 15 15 -
applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/CreateMultipolygonAction.java
r30737 r30738 28 28 29 29 public CreateMultipolygonAction( ChosenRelation chRel ) { 30 31 32 33 34 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(); 35 35 } 36 36 37 37 public CreateMultipolygonAction() { 38 38 this(null); 39 39 } 40 40 41 41 public static boolean getDefaultPropertyValue( String property ) { 42 43 44 45 46 47 48 49 50 51 52 53 54 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); 55 55 } 56 56 57 57 private boolean getPref( String property ) { 58 58 return Main.pref.getBoolean(PREF_MULTIPOLY + property, getDefaultPropertyValue(property)); 59 59 } 60 60 61 61 public void actionPerformed( ActionEvent e ) { 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 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); 126 126 } 127 127 128 128 @Override 129 129 protected void updateEnabledState() { 130 131 132 133 134 130 if( getCurrentDataSet() == null ) { 131 setEnabled(false); 132 } else { 133 updateEnabledState(getCurrentDataSet().getSelected()); 134 } 135 135 } 136 136 137 137 @Override 138 138 protected void updateEnabledState( Collection<? extends OsmPrimitive> selection ) { 139 140 141 142 143 144 145 146 147 148 149 150 151 152 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); 153 153 } 154 154 … … 157 157 */ 158 158 private void addBoundaryMembers( Relation rel ) { 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 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 } 175 175 } 176 176 … … 179 179 */ 180 180 private List<Command> fixWayTagsForBoundary( Relation rel ) { 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 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; 222 222 } 223 223 static public final List<String> DEFAULT_LINEAR_TAGS = Arrays.asList(new String[] {"barrier", "source"}); 224 224 private static final Set<String> REMOVE_FROM_BOUNDARY_TAGS = new TreeSet<>(Arrays.asList(new String[] { 225 226 225 "boundary", "boundary_type", "type", "admin_level" 226 })); 227 227 228 228 /** … … 232 232 */ 233 233 private List<Command> removeTagsFromInnerWays( Relation relation ) { 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 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; 342 342 } 343 343 … … 348 348 */ 349 349 private boolean askForAdminLevelAndName( Relation rel ) { 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 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; 405 405 } 406 406 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/ReconstructPolygonAction.java
r30737 r30738 42 42 43 43 private static final List<String> IRRELEVANT_KEYS = Arrays.asList(new String[] { 44 44 "source", "created_by", "note"}); 45 45 46 46 public ReconstructPolygonAction( ChosenRelation rel ) { 47 47 super(tr("Reconstruct polygon")); 48 48 putValue(SMALL_ICON, ImageProvider.get("dialogs", "filter")); 49 49 putValue(LONG_DESCRIPTION, "Reconstruct polygon from multipolygon relation"); 50 50 this.rel = rel; 51 51 rel.addChosenRelationListener(this); … … 55 55 public void actionPerformed( ActionEvent e ) { 56 56 Relation r = rel.get(); 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 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<>(); 85 85 Command c = DeleteCommand.delete(Main.main.getEditLayer(), Collections.singleton(r), true, true); 86 86 if( c == null ) 87 87 return; 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 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 145 145 Main.main.undoRedo.add(new SequenceCommand(tr("Reconstruct polygons from relation {0}", 146 147 146 r.getDisplayName(DefaultNameFormatter.getInstance())), commands)); 147 Main.main.getCurrentDataSet().setSelected(newSelection); 148 148 } 149 149 150 150 public void chosenRelationChanged( Relation oldRelation, Relation newRelation ) { 151 151 setEnabled(isSuitableRelation(newRelation)); 152 152 } 153 153 154 154 private boolean isSuitableRelation( Relation newRelation ) { 155 156 157 158 159 160 161 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 } 163 163 } 164 164 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SortAndFixAction.java
r30737 r30738 25 25 26 26 public class SortAndFixAction extends AbstractAction implements ChosenRelationListener { 27 28 27 private static final long serialVersionUID = 1L; 28 private ChosenRelation rel; 29 29 private List<RelationFixer> fixers; 30 30 … … 67 67 68 68 private RelationFixer getFixer( Relation rel ) { 69 70 71 72 69 for(RelationFixer fixer : fixers) 70 if (fixer.isFixerApplicable(rel)) 71 return fixer; 72 return new NothingFixer(); 73 73 } 74 74 -
applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/SplittingMultipolygons.java
r30737 r30738 24 24 25 25 public static boolean canProcess( Collection<Way> ways ) { 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 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; 68 68 } 69 69 70 70 public static List<Relation> process( Collection<Way> selectedWays ) { 71 // 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 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; 100 100 } 101 101 … … 104 104 */ 105 105 private static void closePolygon( List<Node> base, List<Node> append ) { 106 107 108 109 110 111 112 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); 113 113 } 114 114 … … 117 117 */ 118 118 private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) { 119 120 121 122 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); 123 123 } 124 124 … … 131 131 */ 132 132 public static List<Way> splitWay( Way w, Node n1, Node n2, List<Command> commands ) { 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 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; 217 217 } 218 218 219 219 public static List<Way> splitWay( Way w, Node n1, Node n2 ) { 220 220 return splitWay(w, n1, n2, null); 221 221 } 222 222 … … 225 225 */ 226 226 public static Relation tryToCloseOneWay( Way segment, List<Command> resultingCommands ) { 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 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; 288 288 } 289 289 … … 292 292 */ 293 293 private static <T> List<T> intersection( Collection<T> list1, Collection<T> list2 ) { 294 295 296 297 298 294 List<T> result = new ArrayList<>(); 295 for( T item : list1 ) 296 if( list2.contains(item) ) 297 result.add(item); 298 return result; 299 299 } 300 300 … … 303 303 */ 304 304 public static Relation attachRingToNeighbours( Way ring, List<Command> resultingCommands ) { 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 // 329 330 331 // 332 // 333 // 334 // 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 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(); 355 355 } 356 356 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/actions/TheRing.java
r30737 r30738 36 36 37 37 public TheRing( Way source ) { 38 39 40 38 this.source = source; 39 segments = new ArrayList<>(1); 40 segments.add(new RingSegment(source)); 41 41 } 42 42 43 43 public static boolean areAllOfThoseRings( Collection<Way> ways ) { 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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; 64 64 } 65 65 … … 69 69 */ 70 70 public static List<Relation> makeManySimpleMultipolygons( Collection<Way> selection, List<Command> commands ) { 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 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; 87 87 } 88 88 89 89 public void collide( TheRing other ) { 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 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 } 116 116 } 117 117 … … 120 120 */ 121 121 public static Node[] getSplitNodes( List<Node> nodes1, List<Node> nodes2, boolean isRing1, boolean isRing2 ) { 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 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; 185 185 } 186 186 187 187 private static int incrementBy( int value, int increment, int limit1, boolean isRing ) { 188 189 190 191 192 193 194 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; 195 195 } 196 196 197 197 private boolean areSegmentsEqual( RingSegment seg1, RingSegment seg2 ) { 198 199 200 201 202 203 204 205 206 207 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; 208 208 } 209 209 … … 213 213 */ 214 214 private RingSegment splitRingAt( int segmentIndex, Node n1, Node n2 ) { 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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; 239 239 } 240 240 … … 246 246 */ 247 247 public static void redistributeSegments( List<TheRing> rings ) { 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 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(); 273 273 } 274 274 275 275 private int countNonReferenceSegments() { 276 277 278 279 280 276 int count = 0; 277 for( RingSegment seg : segments ) 278 if( !seg.isReference() ) 279 count++; 280 return count; 281 281 } 282 282 283 283 public void putSourceWayFirst() { 284 285 286 287 288 289 284 for( RingSegment seg : segments ) { 285 if( !seg.isReference() ) { 286 seg.overrideWay(source); 287 return; 288 } 289 } 290 290 } 291 291 292 292 public List<Command> getCommands() { 293 293 return getCommands(true, null); 294 294 } 295 295 296 296 public List<Command> getCommands( Map<Relation, Relation> relationChangeMap ) { 297 297 return getCommands(true, relationChangeMap); 298 298 } 299 299 … … 303 303 */ 304 304 public List<Command> getCommands( boolean createMultipolygon, Map<Relation, Relation> relationChangeMap ) { 305 306 307 308 309 310 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() ) { 311 311 if( linearTags.contains(key) ) continue; 312 312 if( key.equals("natural") && sourceCopy.get("natural").equals("coastline") ) continue; 313 313 relation.put(key, sourceCopy.get(key)); 314 314 sourceCopy.remove(key); 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 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; 372 372 } 373 373 374 374 public static void updateCommandsWithRelations( List<Command> commands, Map<Relation, Relation> relationCache ) { 375 376 375 for( Relation src : relationCache.keySet() ) 376 commands.add(new ChangeCommand(src, relationCache.get(src))); 377 377 } 378 378 … … 381 381 */ 382 382 public Relation getRelation() { 383 383 return relation; 384 384 } 385 385 386 386 @Override 387 387 public String toString() { 388 389 390 391 392 393 394 395 396 397 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(); 398 398 } 399 399 … … 402 402 */ 403 403 /*private static void closePolygon( List<Node> base, List<Node> append ) { 404 405 406 407 408 409 410 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); 411 411 }*/ 412 412 … … 415 415 */ 416 416 /*private static boolean segmentInsidePolygon( Node n1, Node n2, List<Node> polygon ) { 417 418 419 420 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); 421 421 }*/ 422 422 423 423 private static void log( String s ) { 424 // 424 // System.out.println(s); 425 425 } 426 426 427 427 private static class RingSegment { 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 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 } 594 594 } 595 595 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/AssociatedStreetFixer.java
r30737 r30738 19 19 public class AssociatedStreetFixer extends RelationFixer { 20 20 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 } 61 24 62 25 @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 } 70 61 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; 73 70 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); 100 73 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 } 107 100 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; 109 107 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); 120 109 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 } 127 120 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 } 132 127 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 } 139 132 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; 141 139 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?? 145 141 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 } 156 156 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/BoundaryFixer.java
r28762 r30738 16 16 public class BoundaryFixer extends MultipolygonFixer { 17 17 18 19 20 18 public BoundaryFixer() { 19 super("boundary", "multipolygon"); 20 } 21 21 22 23 24 25 26 27 28 29 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 } 31 31 32 33 34 32 @Override 33 public boolean isRelationGood(Relation rel) { 34 for( RelationMember m : rel.getMembers() ) { 35 35 if (m.getType().equals(OsmPrimitiveType.RELATION) && !"subarea".equals(m.getRole())) { 36 36 setWarningMessage(tr("Relation without ''subarea'' role found")); … … 43 43 if (m.getType().equals(OsmPrimitiveType.WAY) && !("outer".equals(m.getRole()) || "inner".equals(m.getRole()))) { 44 44 setWarningMessage(tr("Way without ''inner'' or ''outer'' role found")); 45 45 return false; 46 46 } 47 47 } 48 49 50 48 clearWarningMessage(); 49 return true; 50 } 51 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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 } 68 68 69 69 private Relation fixBoundaryRoles( Relation source ) { 70 70 Relation r = new Relation(source); 71 71 boolean fixed = false; -
applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/MultipolygonFixer.java
r30737 r30738 22 22 public class MultipolygonFixer extends RelationFixer { 23 23 24 25 26 24 public MultipolygonFixer() { 25 super("multipolygon"); 26 } 27 27 28 29 30 28 protected MultipolygonFixer(String...types) { 29 super(types); 30 } 31 31 32 32 33 34 35 36 37 38 39 40 41 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 } 43 43 44 45 46 47 48 44 @Override 45 public Command fixRelation(Relation rel) { 46 Relation rr = fixMultipolygonRoles(rel); 47 return rr != null? new ChangeCommand(rel, rr) : null; 48 } 49 49 50 50 /** 51 51 * Basically, created multipolygon from scratch, and if successful, replace roles with new ones. 52 52 */ -
applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/NothingFixer.java
r28693 r30738 9 9 public class NothingFixer extends RelationFixer { 10 10 11 12 13 14 15 16 17 18 19 20 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 } 22 22 23 24 25 26 23 @Override 24 public Command fixRelation(Relation rel) { 25 return null; 26 } 27 27 28 28 } -
applications/editors/josm/plugins/reltoolbox/src/relcontext/relationfix/RelationFixer.java
r30737 r30738 15 15 public abstract class RelationFixer { 16 16 17 18 17 private List<String> applicableTypes; 18 private SortAndFixAction sortAndFixAction; 19 19 20 21 22 23 24 25 26 27 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 } 30 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 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; 45 45 46 47 48 49 46 String type = rel.get("type"); 47 for(String oktype: applicableTypes) 48 if (oktype.equals(type)) 49 return true; 50 50 51 52 51 return false; 52 } 53 53 54 55 56 57 58 59 60 61 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); 62 62 63 64 65 66 67 68 69 70 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); 71 71 72 72 public void setFixAction(SortAndFixAction sortAndFixAction) { -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignInputDialog.java
r30737 r30738 68 68 import org.openstreetmap.josm.gui.ExtendedDialog; 69 69 import org.openstreetmap.josm.gui.widgets.MultiSplitLayout; 70 import org.openstreetmap.josm.gui.widgets.MultiSplitLayout.Node; 70 71 import org.openstreetmap.josm.gui.widgets.MultiSplitPane; 71 import org.openstreetmap.josm.gui.widgets.MultiSplitLayout.Node;72 72 import org.openstreetmap.josm.plugins.roadsigns.RoadSignsPlugin.PresetMetaData; 73 73 import org.openstreetmap.josm.plugins.roadsigns.Sign.SignParameter; … … 103 103 protected JEditorPane info; 104 104 protected JScrollPane scrollInfo; 105 105 106 106 private MultiSplitPane multiSplitPane; 107 107 … … 150 150 Node model = multiSplitPane.getMultiSplitLayout().getModel(); 151 151 File f = new File(RoadSignsPlugin.pluginDir(), "roadsigns-layout.xml"); 152 try {152 try ( 153 153 XMLEncoder xmlenc = new XMLEncoder( 154 154 new BufferedOutputStream(new FileOutputStream(f)) 155 ) ;155 )) { 156 156 xmlenc.writeObject(model); 157 xmlenc.close();158 157 } catch (FileNotFoundException ex) { 159 158 Main.warn("unable to write dialog layout: "+ex); … … 163 162 super.setVisible(visible); 164 163 } 165 166 164 167 165 private Command createCommand(Collection<OsmPrimitive> selPrim) { … … 198 196 199 197 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)))) { 203 200 Node model = (Node) decoder.readObject(); 204 decoder.close();205 201 multiSplitPane.getMultiSplitLayout().setModel(model); 206 202 multiSplitPane.getMultiSplitLayout().setFloatingDividers(false); 207 } 208 catch (Exception ex) { 203 } catch (Exception ex) { 209 204 Node modelRoot = MultiSplitLayout.parseModel(layoutDef); 210 205 multiSplitPane.getMultiSplitLayout().setModel(modelRoot); … … 225 220 info.setBackground(this.getBackground()); 226 221 info.addHyperlinkListener(new HyperlinkListener() { 227 public void hyperlinkUpdate(HyperlinkEvent e) { 222 @Override 223 public void hyperlinkUpdate(HyperlinkEvent e) { 228 224 if (e == null || e.getURL() == null) 229 225 return; 230 System.out.println(e.getURL());231 226 if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { 232 227 OpenBrowser.displayUrl(e.getURL().toString()); … … 472 467 } 473 468 class TFDocumentListener implements DocumentListener { 474 public void insertUpdate(DocumentEvent e) { 469 @Override 470 public void insertUpdate(DocumentEvent e) { 475 471 update(); 476 472 } 477 473 478 public void removeUpdate(DocumentEvent e) { 474 @Override 475 public void removeUpdate(DocumentEvent e) { 479 476 update(); 480 477 } 481 478 482 public void changedUpdate(DocumentEvent e) { 479 @Override 480 public void changedUpdate(DocumentEvent e) { 483 481 update(); 484 482 } … … 540 538 String[][] data = {{}}; 541 539 previewTable = new JTable(data, columnNames) { 542 public String getToolTipText(MouseEvent e) { 540 @Override 541 public String getToolTipText(MouseEvent e) { 543 542 int rowIndex = rowAtPoint(e.getPoint()); 544 543 int colIndex = columnAtPoint(e.getPoint()); … … 564 563 addTrafficSignTag.setSelected(Main.pref.getBoolean("plugin.roadsigns.addTrafficSignTag")); 565 564 addTrafficSignTag.addActionListener(new ActionListener() { 566 public void actionPerformed(ActionEvent e) { 565 @Override 566 public void actionPerformed(ActionEvent e) { 567 567 previewModel.update(); 568 568 } … … 581 581 String[] header = {tr("Key"), tr("Value")}; 582 582 583 public int getRowCount() { 583 @Override 584 public int getRowCount() { 584 585 return keys.size(); 585 586 } 586 587 587 public int getColumnCount() { 588 @Override 589 public int getColumnCount() { 588 590 return 2; 589 591 } 590 592 591 public Object getValueAt(int rowIndex, int columnIndex) { 593 @Override 594 public Object getValueAt(int rowIndex, int columnIndex) { 592 595 if (columnIndex == 0) { 593 596 return keys.get(rowIndex); … … 758 761 /* scroll up again */ 759 762 SwingUtilities.invokeLater(new Runnable(){ 760 public void run() { 763 @Override 764 public void run() { 761 765 scrollInfo.getVerticalScrollBar().setValue(0); 762 766 } … … 818 822 } 819 823 820 public Dimension getPreferredScrollableViewportSize() { 824 @Override 825 public Dimension getPreferredScrollableViewportSize() { 821 826 return super.getPreferredSize(); 822 827 } 823 828 824 public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction ) { 829 @Override 830 public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction ) { 825 831 final int FRAC = 20; 826 832 int inc = (orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth()) / FRAC; … … 828 834 } 829 835 830 public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction ) { 836 @Override 837 public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction ) { 831 838 return orientation == SwingConstants.VERTICAL ? getParent().getHeight() : getParent().getWidth(); 832 839 } 833 840 834 public boolean getScrollableTracksViewportWidth() { 841 @Override 842 public boolean getScrollableTracksViewportWidth() { 835 843 return true; 836 844 } 837 845 838 public boolean getScrollableTracksViewportHeight() { 846 @Override 847 public boolean getScrollableTracksViewportHeight() { 839 848 return false; 840 849 } -
applications/editors/josm/plugins/roadsigns/src/org/openstreetmap/josm/plugins/roadsigns/RoadSignsPlugin.java
r30737 r30738 24 24 import javax.swing.JOptionPane; 25 25 26 import org.xml.sax.SAXException;27 26 import org.openstreetmap.josm.Main; 28 27 import org.openstreetmap.josm.actions.JosmAction; … … 36 35 import org.openstreetmap.josm.tools.Shortcut; 37 36 import org.openstreetmap.josm.tools.Utils; 37 import org.xml.sax.SAXException; 38 38 39 39 public class RoadSignsPlugin extends Plugin { … … 79 79 } 80 80 81 public void actionPerformed(ActionEvent e) { 81 @Override 82 public void actionPerformed(ActionEvent e) { 82 83 String code = Main.pref.get("plugin.roadsigns.preset.selection", null); 83 84 if (code == null) { … … 241 242 * Returns an inputstream from urls, files and classloaders, depending on the name. 242 243 */ 243 public static InputStream getInputStream(String source) throws IOException { 244 @SuppressWarnings("resource") 245 public static InputStream getInputStream(String source) throws IOException { 244 246 InputStream in = null; 245 247 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 20102 1 eclipse.preferences.version=1 3 2 editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true … … 9 8 sp_cleanup.add_missing_nls_tags=false 10 9 sp_cleanup.add_missing_override_annotations=false 10 sp_cleanup.add_missing_override_annotations_interface_methods=false 11 11 sp_cleanup.add_serial_version_id=false 12 12 sp_cleanup.always_use_blocks=true … … 14 14 sp_cleanup.always_use_this_for_non_static_field_access=false 15 15 sp_cleanup.always_use_this_for_non_static_method_access=false 16 sp_cleanup.convert_functional_interfaces=false 16 17 sp_cleanup.convert_to_enhanced_for_loop=false 17 sp_cleanup.correct_indentation= true18 sp_cleanup.correct_indentation=false 18 19 sp_cleanup.format_source_code=false 19 20 sp_cleanup.format_source_code_changes_only=false 21 sp_cleanup.insert_inferred_type_arguments=false 20 22 sp_cleanup.make_local_variable_final=false 21 23 sp_cleanup.make_parameters_final=false … … 33 35 sp_cleanup.qualify_static_method_accesses_with_declaring_class=false 34 36 sp_cleanup.remove_private_constructors=true 37 sp_cleanup.remove_redundant_type_arguments=false 35 38 sp_cleanup.remove_trailing_whitespaces=true 36 39 sp_cleanup.remove_trailing_whitespaces_all=true … … 46 49 sp_cleanup.sort_members=false 47 50 sp_cleanup.sort_members_all=false 51 sp_cleanup.use_anonymous_class_creation=false 48 52 sp_cleanup.use_blocks=false 49 53 sp_cleanup.use_blocks_only_for_return_and_throw=false 54 sp_cleanup.use_lambda=false 50 55 sp_cleanup.use_parentheses_in_expressions=false 51 56 sp_cleanup.use_this_for_non_static_field_access=false … … 53 58 sp_cleanup.use_this_for_non_static_method_access=false 54 59 sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true 60 sp_cleanup.use_type_arguments=false -
applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/RoutesPlugin.java
r30737 r30738 19 19 import org.openstreetmap.josm.gui.layer.Layer; 20 20 import org.openstreetmap.josm.gui.layer.OsmDataLayer; 21 22 21 import org.openstreetmap.josm.plugins.Plugin; 23 22 import org.openstreetmap.josm.plugins.PluginInformation; … … 36 35 File routesFile = new File(getPluginDir() + File.separator + "routes.xml"); 37 36 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"); 39 38 40 39 try { 41 40 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 } 49 50 } 50 51 outputStream.close();52 inputStream.close();53 54 51 } catch (IOException e) { 55 e.printStackTrace();52 Main.error(e); 56 53 } 57 54 } … … 62 59 Unmarshaller unmarshaller = context.createUnmarshaller(); 63 60 Routes routes = (Routes)unmarshaller.unmarshal( 64 new FileInputStream(getPluginDir() + File.separator + "routes.xml")); 61 new FileInputStream(getPluginDir() + File.separator + "routes.xml")); 65 62 for (RoutesXMLLayer layer:routes.getLayer()) { 66 63 if (layer.isEnabled()) { … … 77 74 78 75 public void activeLayerChange(Layer oldLayer, Layer newLayer) { 79 // TODO Auto-generated method stub76 // Do nothing 80 77 } 81 78 … … 117 114 checkLayers(); 118 115 } 119 120 116 } -
applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/paint/AbstractLinePainter.java
r23422 r30738 17 17 public abstract class AbstractLinePainter implements PathPainter { 18 18 19 20 21 22 23 24 25 26 27 28 29 30 31 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; 32 32 33 33 double ua = (dx2 * (y1 - y3) - dy2 * (x1 - x3)) / (dy2 * dx1 - dx2 * dy1); 34 34 35 36 37 38 39 40 41 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 } 43 43 44 45 44 return true; 45 } 46 46 47 48 49 50 47 protected double det(double a, double b, double c, double d) 48 { 49 return a * d - b * c; 50 } 51 51 52 53 54 52 protected Point shiftPoint(Point2D p1, Point2D p2, double shift) { 53 double dx = p2.getX() - p1.getX(); 54 double dy = p2.getY() - p1.getY(); 55 55 56 57 58 56 // Perpendicular vector 57 double ndx = -dy; 58 double ndy = dx; 59 59 60 61 62 63 60 // Normalize 61 double length = Math.sqrt(ndx * ndx + ndy * ndy); 62 ndx = ndx / length; 63 ndy = ndy / length; 64 64 65 66 65 return new Point((int)(p1.getX() + shift * ndx), (int)(p1.getY() + shift * ndy)); 66 } 67 67 68 69 70 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(); 71 71 72 73 72 Point2D point1 = shiftPoint(p1, p2, shift); 73 Point2D point2 = new Point2D.Double(point1.getX() + dx, point1.getY() + dy); 74 74 75 76 77 75 return new Line2D.Double( 76 point1, point2); 77 } 78 78 79 79 protected GeneralPath getPath(Graphics2D g, MapView mapView, List<Node> nodes, double shift) { 80 80 81 81 GeneralPath path = new GeneralPath(); 82 82 83 84 85 83 if (nodes.size() < 2) { 84 return path; 85 } 86 86 87 88 89 90 87 Point p1 = null; 88 Point p2 = null; 89 Point p3 = null; 90 Point lastPoint = null; 91 91 92 93 92 for (Node n: nodes) { 93 Point p = mapView.getPoint(n); 94 94 95 96 97 98 99 100 101 95 if (!p.equals(p3)) { 96 p1 = p2; 97 p2 = p3; 98 p3 = p; 99 } else { 100 continue; 101 } 102 102 103 104 105 106 107 108 109 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); 110 110 111 111 /*path.moveTo((float)line1.x1, (float)line1.y1); 112 112 path.lineTo((float)line1.x2, (float)line1.y2); 113 113 path.moveTo((float)line2.x1, (float)line2.y1); 114 114 path.lineTo((float)line2.x2, (float)line2.y2);*/ 115 115 116 117 118 119 120 121 122 123 124 125 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 } 130 130 131 132 133 134 135 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 } 138 138 139 140 141 142 139 if (p2 != null && p3 != null && lastPoint != null) { 140 p3 = shiftPoint(p3, p2, -shift); 141 drawSegment(g, mapView, path, lastPoint, p3); 142 } 143 143 144 145 144 return path; 145 } 146 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 } 171 171 172 173 174 175 176 177 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 } 179 179 180 180 -
applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xml
r19345 r30738 2 2 <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 "> 3 3 <!-- pattern is the same pattern as used in SearchAction --> 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 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> 33 33 </routes> -
applications/editors/josm/plugins/routes/src/org/openstreetmap/josm/plugins/routes/xml/routes.xsd
r16593 r30738 11 11 12 12 <annotation> 13 14 15 16 17 18 19 13 <appinfo> 14 <jxb:schemaBindings> 15 <jxb:nameXmlTransform> 16 <jxb:typeName prefix="RoutesXML"/> 17 </jxb:nameXmlTransform> 18 </jxb:schemaBindings> 19 </appinfo> 20 20 </annotation> 21 21 22 22 <element name="routes"> 23 24 25 26 27 23 <complexType> 24 <sequence> 25 <element name="layer" type="tns:layer" minOccurs="0" maxOccurs="unbounded"/> 26 </sequence> 27 </complexType> 28 28 </element> 29 29 30 30 <complexType name="layer"> 31 32 33 34 35 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"/> 36 36 </complexType> 37 37 38 38 <complexType name="route"> 39 40 41 42 43 39 <sequence> 40 <element name="pattern" type="string"/> 41 </sequence> 42 <attribute name="color" type="string"/> 43 <attribute name="enabled" type="boolean" default="true"/> 44 44 </complexType> 45 45 -
applications/editors/josm/plugins/sds/.settings/org.eclipse.jdt.core.prefs
r30736 r30738 40 40 org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore 41 41 org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled 42 org.eclipse.jdt.core.compiler.problem.missingSerialVersion= warning42 org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore 43 43 org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore 44 44 org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/DetermineSdsModificationsUploadHook.java
r30737 r30738 32 32 public class DetermineSdsModificationsUploadHook implements UploadHook 33 33 { 34 34 private SeparateDataStorePlugin plugin; 35 35 36 37 38 39 36 DetermineSdsModificationsUploadHook(SeparateDataStorePlugin plugin) { 37 this.plugin = plugin; 38 } 39 40 40 public boolean checkUpload(APIDataSet apiDataSet) { 41 42 43 44 45 46 47 48 49 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 } 52 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 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 } 71 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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; 162 162 163 163 } 164 164 165 165 boolean hasSpecialTags(IPrimitive p) { 166 167 168 169 166 for (String key : p.keySet()) { 167 if (isSpecialKey(key)) return true; 168 } 169 return false; 170 170 } 171 171 172 172 boolean isSpecialKey(String key) { 173 173 return key.startsWith(plugin.getIgnorePrefix()); 174 174 } 175 175 } -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/ReadPostprocessor.java
r30737 r30738 24 24 25 25 public class ReadPostprocessor implements OsmServerReadPostprocessor { 26 27 28 29 30 31 26 27 private ArrayList<Long> nodeList; 28 private ArrayList<Long> wayList; 29 private ArrayList<Long> relationList; 30 31 private SeparateDataStorePlugin plugin; 32 32 33 34 35 36 33 public ReadPostprocessor(SeparateDataStorePlugin plugin) { 34 this.plugin = plugin; 35 } 36 37 37 @Override 38 38 public void postprocessDataSet(DataSet ds, ProgressMonitor progress) { 39 39 40 41 42 40 nodeList = new ArrayList<>(); 41 wayList = new ArrayList<>(); 42 relationList = new ArrayList<>(); 43 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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. 80 80 InputStream xmlStream; 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 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 } 98 98 99 99 } -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsApi.java
r30737 r30738 34 34 * 35 35 * This is modeled after JOSM's own OsmAPI class. 36 * 36 * 37 37 */ 38 38 public class SdsApi extends SdsConnection { … … 42 42 /** the collection of instantiated OSM APIs */ 43 43 private static HashMap<String, SdsApi> instances = new HashMap<>(); 44 44 45 45 /** 46 46 * replies the {@see OsmApi} for a given server URL … … 123 123 * @param osm the primitive 124 124 * @throws SdsTransferException if something goes wrong 125 125 126 126 public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException { 127 127 String ret = ""; … … 144 144 * @param monitor the progress monitor 145 145 * @throws SdsTransferException if something goes wrong 146 146 147 147 public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException { 148 148 String ret = null; … … 165 165 * @param osm the primitive 166 166 * @throws SdsTransferException if something goes wrong 167 167 168 168 public void deletePrimitive(IPrimitive osm, ProgressMonitor monitor) throws SdsTransferException { 169 169 ensureValidChangeset(); … … 182 182 * @param list the list of changed OSM Primitives 183 183 * @param monitor the progress monitor 184 * @return 184 * @return 185 185 * @return list of processed primitives 186 * @throws SdsTransferException 186 * @throws SdsTransferException 187 187 * @throws SdsTransferException if something is wrong 188 188 189 189 public Collection<IPrimitive> uploadDiff(Collection<? extends IPrimitive> list, ProgressMonitor monitor) throws SdsTransferException { 190 190 try { … … 227 227 } 228 228 */ 229 229 230 230 public String requestShadowsFromSds(List<Long> nodes, List<Long> ways, List<Long> relations, ProgressMonitor pm) throws SdsTransferException { 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 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 272 272 } 273 273 … … 304 304 return sendRequest(requestMethod, urlSuffix, requestBody, monitor, doAuth, false); 305 305 } 306 306 307 307 public boolean updateSds(String message, ProgressMonitor pm) { 308 309 310 311 312 313 314 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; 315 315 } 316 316 … … 352 352 activeConnection.setDoOutput(true); 353 353 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 } 366 367 } 367 out.close();368 368 } 369 369 … … 442 442 } 443 443 } 444 444 445 445 protected InputStream getInputStream(String urlStr, ProgressMonitor progressMonitor) throws SdsTransferException { 446 446 urlStr = getBaseUrl() + urlStr; 447 447 try { 448 448 URL url = null; 449 449 try { -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsConnection.java
r29854 r30738 21 21 */ 22 22 public class SdsConnection { 23 23 24 24 protected boolean cancel = false; 25 25 protected HttpURLConnection activeConnection; -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsCredentialAgent.java
r30737 r30738 120 120 } 121 121 122 123 124 125 126 127 128 122 @Override 123 public void storeOAuthAccessToken(OAuthToken accessToken) 124 throws CredentialsAgentException { 125 // no-op 126 127 } 128 129 129 @Override 130 130 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 11 11 public class SdsCredentialDialog extends CredentialDialog { 12 12 13 13 static public SdsCredentialDialog getSdsApiCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) { 14 14 SdsCredentialDialog dialog = new SdsCredentialDialog(saveUsernameAndPasswordCheckboxText); 15 15 dialog.prepareForSdsApiCredentials(username, password); … … 21 21 22 22 public SdsCredentialDialog(String saveUsernameAndPasswordCheckboxText) { 23 23 super(saveUsernameAndPasswordCheckboxText); 24 24 } 25 25 26 26 public void prepareForSdsApiCredentials(String username, String password) { 27 27 setTitle(tr("Enter credentials for Separate Data Store API")); … … 33 33 private static class SdsApiCredentialsPanel extends CredentialPanel { 34 34 35 35 @Override 36 36 protected void build() { 37 37 super.build(); -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsDiskAccessAction.java
r30666 r30738 16 16 @SuppressWarnings("serial") 17 17 public abstract class SdsDiskAccessAction extends DiskAccessAction { 18 18 19 19 public SdsDiskAccessAction(String name, String iconName, String tooltip, 20 21 22 20 Shortcut shortcut) { 21 super(name, iconName, tooltip, shortcut); 22 } 23 23 24 24 public static SwingFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title) { 25 25 String curDir = Main.pref.get("lastDirectory"); 26 26 if (curDir.equals("")) { … … 35 35 fc.setMultiSelectionEnabled(multiple); 36 36 fc.setAcceptAllFileFilterUsed(false); 37 37 38 38 fc.setFileFilter(new FileFilter() { 39 40 39 public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); } 40 public String getDescription() { return (tr("SDS data file")); } 41 41 }); 42 42 … … 83 83 84 84 fc.setFileFilter(new FileFilter() { 85 86 85 public boolean accept(File pathname) { return pathname.getName().endsWith(".sds") || pathname.isDirectory(); } 86 public String getDescription() { return (tr("SDS data file")); } 87 87 }); 88 88 -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsLoadAction.java
r30737 r30738 26 26 @SuppressWarnings("serial") 27 27 public class SdsLoadAction extends SdsDiskAccessAction { 28 29 28 29 private SeparateDataStorePlugin plugin; 30 30 31 31 public SdsLoadAction(SeparateDataStorePlugin p) { 32 32 super(tr("Load..."), "sds_load", tr("Load separate data store data from a file."), null); 33 33 plugin = p; 34 34 } 35 35 -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsMenu.java
r29854 r30738 56 56 57 57 void setEnabledState() { 58 59 60 58 boolean en = (Main.map != null) && (Main.map.mapView != null) && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer); 59 loadItem.setEnabled(en); 60 saveItem.setEnabled(en); 61 61 } 62 62 63 64 63 @Override 64 public void activeLayerChange(Layer oldLayer, Layer newLayer) { setEnabledState(); } 65 65 66 67 66 @Override 67 public void layerAdded(Layer newLayer) { setEnabledState(); } 68 68 69 70 69 @Override 70 public void layerRemoved(Layer oldLayer) { setEnabledState(); } 71 71 72 72 private class SdsAboutAction extends JosmAction { 73 73 74 75 76 74 public SdsAboutAction() { 75 super(tr("About"), "sds", tr("Information about SDS."), null, true); 76 } 77 77 78 79 78 public void actionPerformed(ActionEvent e) { 79 JPanel about = new JPanel(); 80 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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)); 103 103 104 105 106 107 108 109 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 { 110 110 111 112 113 114 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 } 116 116 117 118 119 120 121 122 117 /** 118 * Launch the preferences dialog. 119 */ 120 public void actionPerformed(ActionEvent e) { 121 run(); 122 } 123 123 124 125 126 127 128 129 130 131 132 133 134 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 } 137 137 138 138 -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriter.java
r30737 r30738 27 27 public class SdsOsmWriter extends OsmWriter { 28 28 29 30 29 private SeparateDataStorePlugin plugin; 30 31 31 public SdsOsmWriter(SeparateDataStorePlugin plugin, PrintWriter out, boolean osmConform, String version) { 32 32 super(out, osmConform, version); … … 43 43 Collections.sort(entries, byKeyComparator); 44 44 for (Entry<String, String> e : entries) { 45 45 String key = e.getKey(); 46 46 if (!(osm instanceof Changeset) && ("created_by".equals(key))) continue; 47 47 if (key.startsWith(plugin.getIgnorePrefix())) continue; -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsOsmWriterFactory.java
r28160 r30738 15 15 public class SdsOsmWriterFactory extends OsmWriterFactory { 16 16 17 18 19 20 21 22 23 17 SeparateDataStorePlugin plugin; 18 19 public SdsOsmWriterFactory(SeparateDataStorePlugin plugin) { 20 this.plugin = plugin; 21 } 22 23 @Override 24 24 protected OsmWriter createOsmWriterImpl(PrintWriter out, boolean osmConform, String version) { 25 25 return new SdsOsmWriter(plugin, out, osmConform, version); -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsParser.java
r28160 r30738 54 54 { 55 55 String type = atts.getValue("osm_type"); 56 String id = atts.getValue("osm_id"); 56 String id = atts.getValue("osm_id"); 57 57 currentPrimitive = dataSet.getPrimitiveById(Long.parseLong(id), OsmPrimitiveType.fromApiTypeName(type)); 58 58 if (currentPrimitive == null && ensureMatch) { -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsPluginPreferences.java
r28160 r30738 35 35 36 36 public SdsPluginPreferences() { 37 37 super("sds", tr("Separate Data Store"), tr("Configures access to the Separate Data Store.")); 38 38 } 39 39 @Override 40 40 public void addGui(final PreferenceTabbedPane gui) { 41 41 final JPanel tab = gui.createPreferenceTab(this); 42 42 43 43 final JPanel access = new JPanel(new GridBagLayout()); 44 44 access.setBorder(BorderFactory.createTitledBorder(tr("Server"))); -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsSaveAction.java
r29854 r30738 6 6 import java.awt.event.ActionEvent; 7 7 import java.io.File; 8 import java.io.FileInputStream;9 import java.io.FileNotFoundException;10 8 import java.io.FileOutputStream; 11 9 import java.io.IOException; … … 21 19 import org.openstreetmap.josm.gui.layer.Layer; 22 20 import org.openstreetmap.josm.gui.layer.OsmDataLayer; 21 import org.openstreetmap.josm.tools.Utils; 23 22 24 @SuppressWarnings("serial")25 23 public class SdsSaveAction extends SdsDiskAccessAction { 26 24 … … 30 28 } 31 29 30 @Override 32 31 public void actionPerformed(ActionEvent e) { 33 32 if (!isEnabled()) … … 40 39 if (Main.isDisplayingMapView() && (Main.map.mapView.getActiveLayer() instanceof OsmDataLayer)) 41 40 layer = Main.map.mapView.getActiveLayer(); 42 41 43 42 if (layer == null) 44 43 return false; … … 64 63 if (file.exists()) { 65 64 tmpFile = new File(file.getPath() + "~"); 66 copy(file, tmpFile);65 Utils.copyFile(file, tmpFile); 67 66 } 68 67 … … 70 69 Writer writer = new OutputStreamWriter(out, "UTF-8"); 71 70 72 SdsWriter w = new SdsWriter(new PrintWriter(writer));73 71 layer.data.getReadLock().lock(); 74 try { 72 try (SdsWriter w = new SdsWriter(new PrintWriter(writer))) { 75 73 w.header(); 76 74 for (IPrimitive p : layer.data.allNonDeletedPrimitives()) { … … 78 76 } 79 77 w.footer(); 80 w.close();81 78 } finally { 82 79 layer.data.getReadLock().unlock(); … … 87 84 } 88 85 } catch (IOException e) { 89 e.printStackTrace();86 Main.error(e); 90 87 JOptionPane.showMessageDialog( 91 88 Main.parent, … … 99 96 // be deleted. So, restore the backup if we made one. 100 97 if (tmpFile != null && tmpFile.exists()) { 101 copy(tmpFile, file);98 Utils.copyFile(tmpFile, file); 102 99 } 103 100 } catch (IOException e2) { 104 e2.printStackTrace();101 Main.error(e2); 105 102 JOptionPane.showMessageDialog( 106 103 Main.parent, … … 113 110 return true; 114 111 } 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}", e124 .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 }135 112 } -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SdsWriter.java
r28160 r30738 29 29 30 30 public void write(IPrimitive what, Map<String,String> tags) { 31 32 33 34 35 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("\">"); 36 36 37 38 39 40 41 42 43 44 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>"); 45 45 } 46 46 -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/SeparateDataStorePlugin.java
r30737 r30738 29 29 { 30 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 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 56 56 /** 57 57 * Creates the plugin … … 60 60 { 61 61 super(info); 62 63 64 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: 65 65 OsmReader.registerPostprocessor(new ReadPostprocessor(this)); 66 66 … … 79 79 } 80 80 81 81 public String getIgnorePrefix() { 82 82 return Main.pref.get("sds-server.tag-prefix", "hot:"); 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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 } 130 130 131 131 public PreferenceSetting getPreferenceSetting() { -
applications/editors/josm/plugins/sds/src/org/openstreetmap/hot/sds/WritePostprocessor.java
r29854 r30738 13 13 public class WritePostprocessor implements OsmServerWritePostprocessor { 14 14 15 15 SeparateDataStorePlugin plugin; 16 16 17 18 19 } 17 public WritePostprocessor(SeparateDataStorePlugin plugin) { 18 this.plugin = plugin; 19 } 20 20 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) { 48 23 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; 51 28 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 } 62 39 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 } 73 71 74 72 } -
applications/editors/josm/plugins/smed/src/panels/PanelChan.java
r29894 r30738 28 28 panelStbd.setVisible(false); 29 29 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); 32 32 topmarkButton.setVisible(false); 33 33 lightButton.setVisible(false); 34 Shp shp = dlg.panelMain.mark.getShape();34 Shp shp = SmedAction.panelMain.mark.getShape(); 35 35 if (portButton.isSelected()) { 36 dlg.panelMain.mark.setCategory(Cat.LAM_PORT);36 SmedAction.panelMain.mark.setCategory(Cat.LAM_PORT); 37 37 if (panelPort.shapes.containsKey(shp)) { 38 38 panelPort.shapes.get(shp).setSelected(true); 39 39 } else { 40 40 panelPort.shapeButtons.clearSelection(); 41 dlg.panelMain.mark.setShape(Shp.UNKSHP);41 SmedAction.panelMain.mark.setShape(Shp.UNKSHP); 42 42 } 43 43 panelPort.alShape.actionPerformed(null); … … 48 48 } 49 49 if (stbdButton.isSelected()) { 50 dlg.panelMain.mark.setCategory(Cat.LAM_STBD);50 SmedAction.panelMain.mark.setCategory(Cat.LAM_STBD); 51 51 if (panelStbd.shapes.containsKey(shp)) { 52 52 panelStbd.shapes.get(shp).setSelected(true); 53 53 } else { 54 54 panelStbd.shapeButtons.clearSelection(); 55 dlg.panelMain.mark.setShape(Shp.UNKSHP);55 SmedAction.panelMain.mark.setShape(Shp.UNKSHP); 56 56 } 57 57 panelStbd.alShape.actionPerformed(null); … … 62 62 } 63 63 if (prefStbdButton.isSelected()) { 64 dlg.panelMain.mark.setCategory(Cat.LAM_PSTBD);64 SmedAction.panelMain.mark.setCategory(Cat.LAM_PSTBD); 65 65 if (panelPort.shapes.containsKey(shp)) { 66 66 panelPort.shapes.get(shp).setSelected(true); 67 67 } else { 68 68 panelPort.shapeButtons.clearSelection(); 69 dlg.panelMain.mark.setShape(Shp.UNKSHP);69 SmedAction.panelMain.mark.setShape(Shp.UNKSHP); 70 70 } 71 71 panelPort.alShape.actionPerformed(null); … … 76 76 } 77 77 if (prefPortButton.isSelected()) { 78 dlg.panelMain.mark.setCategory(Cat.LAM_PPORT);78 SmedAction.panelMain.mark.setCategory(Cat.LAM_PPORT); 79 79 if (panelStbd.shapes.containsKey(shp)) { 80 80 panelStbd.shapes.get(shp).setSelected(true); 81 81 } else { 82 82 panelStbd.shapeButtons.clearSelection(); 83 dlg.panelMain.mark.setShape(Shp.UNKSHP);83 SmedAction.panelMain.mark.setShape(Shp.UNKSHP); 84 84 } 85 85 panelStbd.alShape.actionPerformed(null); … … 90 90 } 91 91 if (safeWaterButton.isSelected()) { 92 dlg.panelMain.mark.setCategory(Cat.NOCAT);92 SmedAction.panelMain.mark.setCategory(Cat.NOCAT); 93 93 panelSaw.setVisible(true); 94 94 if (panelSaw.shapes.containsKey(shp)) { … … 96 96 } else { 97 97 panelSaw.shapeButtons.clearSelection(); 98 dlg.panelMain.mark.setShape(Shp.UNKSHP);98 SmedAction.panelMain.mark.setShape(Shp.UNKSHP); 99 99 } 100 100 panelSaw.alShape.actionPerformed(null); … … 104 104 safeWaterButton.setBorderPainted(false); 105 105 } 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(); 109 109 } 110 110 }; … … 113 113 public void actionPerformed(java.awt.event.ActionEvent e) { 114 114 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); 119 119 } else { 120 120 switch (dlg.panelMain.mark.getCategory()) { -
applications/editors/josm/plugins/smed/src/panels/PanelChr.java
r30737 r30738 67 67 } 68 68 String str = charBox.getText(); 69 dlg.panelMain.mark.setLightAtt(Att.CHR, 0, str);69 SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, str); 70 70 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); 73 73 } 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))); 75 75 } 76 76 } … … 80 80 public void focusLost(java.awt.event.FocusEvent e) { 81 81 String str = charBox.getText(); 82 dlg.panelMain.mark.setLightAtt(Att.CHR, 0, str);82 SmedAction.panelMain.mark.setLightAtt(Att.CHR, 0, str); 83 83 EnumSet<Chr> set = EnumSet.noneOf(Chr.class); 84 84 for (EnumSet<Chr> map : SeaMark.ChrMAP.keySet()) { … … 99 99 } 100 100 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); 103 103 } 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))); 105 105 } 106 106 } … … 141 141 142 142 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); 144 144 charBox.setText(str); 145 145 EnumSet<Chr> set = EnumSet.noneOf(Chr.class); … … 151 151 } 152 152 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))); 154 154 } 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))); 156 156 } 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))); 158 158 for (Chr chr : buttons.keySet()) { 159 159 JToggleButton button = buttons.get(chr); -
applications/editors/josm/plugins/smed/src/panels/PanelCol.java
r30737 r30738 41 41 if (button.isSelected()) { 42 42 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)); 48 48 } 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)); 51 51 } 52 52 } 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)); 56 56 } 57 57 button.setBorderPainted(true); 58 58 } else { 59 59 if (button == delButton) { 60 dlg.panelMain.mark.subColour(ent, stackIdx);60 SmedAction.panelMain.mark.subColour(ent, stackIdx); 61 61 } else if (button == addButton) { 62 62 if (stackCol.size() != 0) 63 63 stackIdx++; 64 64 if (stackCol.size() == 0) 65 dlg.panelMain.mark.setColour(ent, col);65 SmedAction.panelMain.mark.setColour(ent, col); 66 66 else 67 switch ( dlg.panelMain.mark.getPattern(ent)) {67 switch (SmedAction.panelMain.mark.getPattern(ent)) { 68 68 case NOPAT: 69 69 break; … … 71 71 case CROSS: 72 72 if (stackCol.size() < 2) 73 dlg.panelMain.mark.addColour(ent, stackIdx, col);73 SmedAction.panelMain.mark.addColour(ent, stackIdx, col); 74 74 break; 75 75 case SQUARED: 76 76 if (stackCol.size() < 4) 77 dlg.panelMain.mark.addColour(ent, stackIdx, col);77 SmedAction.panelMain.mark.addColour(ent, stackIdx, col); 78 78 break; 79 79 default: 80 dlg.panelMain.mark.addColour(ent, stackIdx, col);80 SmedAction.panelMain.mark.addColour(ent, stackIdx, col); 81 81 break; 82 82 } 83 83 } else { 84 dlg.panelMain.mark.setColour(ent, stackIdx, col);84 SmedAction.panelMain.mark.setColour(ent, stackIdx, col); 85 85 } 86 86 syncPanel(); … … 150 150 for (Col col : colours.keySet()) { 151 151 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) { 153 153 button.setBorderPainted(true); 154 154 } else … … 157 157 } else { 158 158 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++) { 160 160 if (stackCol.size() <= idx) { 161 161 stackCol.add(idx, new JRadioButton(new ImageIcon(getClass().getResource("/images/ColourButton.png")))); … … 185 185 JRadioButton btnI = stackCol.get(idx); 186 186 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))); 188 188 if (stackIdx == idx) { 189 189 btnI.setBorderPainted(true); -
applications/editors/josm/plugins/smed/src/panels/PanelFog.java
r30737 r30738 30 30 JRadioButton button = fogs.get(fog); 31 31 if (button.isSelected()) { 32 dlg.panelMain.mark.setFogSound(fog);32 SmedAction.panelMain.mark.setFogSound(fog); 33 33 button.setBorderPainted(true); 34 34 } else … … 41 41 private FocusListener flGroup = new FocusAdapter() { 42 42 public void focusLost(java.awt.event.FocusEvent e) { 43 dlg.panelMain.mark.setFogGroup(groupBox.getText());43 SmedAction.panelMain.mark.setFogGroup(groupBox.getText()); 44 44 } 45 45 }; … … 48 48 private FocusListener flPeriod = new FocusAdapter() { 49 49 public void focusLost(java.awt.event.FocusEvent e) { 50 dlg.panelMain.mark.setFogPeriod(periodBox.getText());50 SmedAction.panelMain.mark.setFogPeriod(periodBox.getText()); 51 51 } 52 52 }; … … 55 55 private FocusListener flSeq = new FocusAdapter() { 56 56 public void focusLost(java.awt.event.FocusEvent e) { 57 dlg.panelMain.mark.setFogSequence(seqBox.getText());57 SmedAction.panelMain.mark.setFogSequence(seqBox.getText()); 58 58 } 59 59 }; … … 62 62 private FocusListener flRange = new FocusAdapter() { 63 63 public void focusLost(java.awt.event.FocusEvent e) { 64 dlg.panelMain.mark.setFogRange(rangeBox.getText());64 SmedAction.panelMain.mark.setFogRange(rangeBox.getText()); 65 65 } 66 66 }; … … 120 120 for (Fog fog : fogs.keySet()) { 121 121 JRadioButton button = fogs.get(fog); 122 button.setBorderPainted( dlg.panelMain.mark.getFogSound() == fog);122 button.setBorderPainted(SmedAction.panelMain.mark.getFogSound() == fog); 123 123 } 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()); 128 128 } 129 129 -
applications/editors/josm/plugins/smed/src/panels/PanelHaz.java
r30737 r30738 24 24 private ActionListener alCat = new ActionListener() { 25 25 public void actionPerformed(java.awt.event.ActionEvent e) { 26 dlg.panelMain.mark.setObjPattern(Pat.HSTRP);26 SmedAction.panelMain.mark.setObjPattern(Pat.HSTRP); 27 27 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); 31 31 northButton.setBorderPainted(true); 32 32 } else { … … 34 34 } 35 35 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); 39 39 southButton.setBorderPainted(true); 40 40 } else { … … 42 42 } 43 43 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); 48 48 eastButton.setBorderPainted(true); 49 49 } else { … … 51 51 } 52 52 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); 57 57 westButton.setBorderPainted(true); 58 58 } else { … … 60 60 } 61 61 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); 66 66 isolButton.setBorderPainted(true); 67 67 } else { 68 68 isolButton.setBorderPainted(false); 69 69 } 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(); 73 73 } 74 74 }; … … 90 90 JRadioButton button = shapes.get(shp); 91 91 if (button.isSelected()) { 92 dlg.panelMain.mark.setShape(shp);92 SmedAction.panelMain.mark.setShape(shp); 93 93 if (isolButton.isSelected()) 94 dlg.panelMain.mark.setObject(isdObjects.get(shp));94 SmedAction.panelMain.mark.setObject(isdObjects.get(shp)); 95 95 else 96 dlg.panelMain.mark.setObject(carObjects.get(shp));96 SmedAction.panelMain.mark.setObject(carObjects.get(shp)); 97 97 button.setBorderPainted(true); 98 98 } else 99 99 button.setBorderPainted(false); 100 100 } 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()); 103 103 } 104 104 }; … … 107 107 public void actionPerformed(java.awt.event.ActionEvent e) { 108 108 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()) { 112 112 case CAM_NORTH: 113 dlg.panelMain.mark.setTopmark(Top.NORTH);113 SmedAction.panelMain.mark.setTopmark(Top.NORTH); 114 114 break; 115 115 case CAM_SOUTH: 116 dlg.panelMain.mark.setTopmark(Top.SOUTH);116 SmedAction.panelMain.mark.setTopmark(Top.SOUTH); 117 117 break; 118 118 case CAM_EAST: 119 dlg.panelMain.mark.setTopmark(Top.EAST);119 SmedAction.panelMain.mark.setTopmark(Top.EAST); 120 120 break; 121 121 case CAM_WEST: 122 dlg.panelMain.mark.setTopmark(Top.WEST);122 SmedAction.panelMain.mark.setTopmark(Top.WEST); 123 123 break; 124 124 default: 125 dlg.panelMain.mark.setTopmark(Top.SPHERES2);125 SmedAction.panelMain.mark.setTopmark(Top.SPHERES2); 126 126 break; 127 127 } 128 128 topmarkButton.setBorderPainted(true); 129 129 } 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); 133 133 topmarkButton.setBorderPainted(false); 134 134 } 135 dlg.panelMain.panelTop.syncPanel();135 SmedAction.panelMain.panelTop.syncPanel(); 136 136 } 137 137 }; … … 140 140 public void actionPerformed(java.awt.event.ActionEvent e) { 141 141 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()) { 144 144 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, ""); 147 147 break; 148 148 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"); 151 151 break; 152 152 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"); 155 155 break; 156 156 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"); 159 159 break; 160 160 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"); 163 163 break; 164 164 } 165 165 lightButton.setBorderPainted(true); 166 166 } else { 167 dlg.panelMain.mark.clrLight();167 SmedAction.panelMain.mark.clrLight(); 168 168 lightButton.setBorderPainted(false); 169 169 } 170 dlg.panelMain.panelLit.syncPanel();170 SmedAction.panelMain.panelLit.syncPanel(); 171 171 } 172 172 }; … … 205 205 206 206 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); 212 212 for (Shp shp : shapes.keySet()) { 213 213 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(); 220 220 lightButton.setBorderPainted(lit); 221 221 lightButton.setSelected(lit); 222 lightButton.setVisible( dlg.panelMain.mark.testValid());222 lightButton.setVisible(SmedAction.panelMain.mark.testValid()); 223 223 } 224 224 -
applications/editors/josm/plugins/smed/src/panels/PanelLights.java
r30737 r30738 25 25 int idx = landCats.get(cat); 26 26 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(); 29 29 } 30 30 } … … 38 38 int idx = trafficCats.get(cat); 39 39 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(); 42 42 } 43 43 } … … 51 51 int idx = warningCats.get(cat); 52 52 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(); 55 55 } 56 56 } … … 64 64 int idx = platformCats.get(cat); 65 65 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(); 68 68 } 69 69 } … … 77 77 int idx = pilotCats.get(cat); 78 78 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(); 81 81 } 82 82 } … … 90 90 int idx = rescueCats.get(cat); 91 91 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(); 94 94 } 95 95 } … … 103 103 int idx = radioCats.get(cat); 104 104 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(); 107 107 } 108 108 } … … 116 116 int idx = radarCats.get(cat); 117 117 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(); 120 120 } 121 121 } … … 130 130 int idx = functions.get(fnc); 131 131 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(); 134 134 } 135 135 } … … 157 157 JRadioButton button = objects.get(obj); 158 158 if (button.isSelected()) { 159 dlg.panelMain.mark.setObject(obj);159 SmedAction.panelMain.mark.setObject(obj); 160 160 button.setBorderPainted(true); 161 161 } else 162 162 button.setBorderPainted(false); 163 163 } 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); 169 169 functionLabel.setVisible(false); 170 170 categoryLabel.setVisible(false); … … 181 181 chLabel.setVisible(false); 182 182 chBox.setVisible(false); 183 dlg.panelMain.mark.setCategory(Cat.NOCAT);183 SmedAction.panelMain.mark.setCategory(Cat.NOCAT); 184 184 if (landButton.isSelected()) { 185 185 functionLabel.setVisible(true); … … 227 227 alRadarCatBox.actionPerformed(null); 228 228 } 229 dlg.panelMain.mark.testValid();229 SmedAction.panelMain.mark.testValid(); 230 230 } 231 231 }; … … 234 234 private FocusListener flCh = new FocusAdapter() { 235 235 public void focusLost(java.awt.event.FocusEvent e) { 236 dlg.panelMain.mark.setChannel(chBox.getText());236 SmedAction.panelMain.mark.setChannel(chBox.getText()); 237 237 } 238 238 }; … … 462 462 chLabel.setVisible(false); 463 463 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))) { 466 466 functionLabel.setVisible(true); 467 467 categoryLabel.setVisible(true); … … 470 470 for (Fnc fnc : functions.keySet()) { 471 471 int item = functions.get(fnc); 472 if ( dlg.panelMain.mark.getFunc() == fnc)472 if (SmedAction.panelMain.mark.getFunc() == fnc) 473 473 functionBox.setSelectedIndex(item); 474 474 } 475 475 for (Cat cat : landCats.keySet()) { 476 476 int item = landCats.get(cat); 477 if ( dlg.panelMain.mark.getCategory() == cat)477 if (SmedAction.panelMain.mark.getCategory() == cat) 478 478 landCatBox.setSelectedIndex(item); 479 479 } 480 } else if ( dlg.panelMain.mark.getObject() == Obj.SISTAT) {480 } else if (SmedAction.panelMain.mark.getObject() == Obj.SISTAT) { 481 481 categoryLabel.setVisible(true); 482 482 trafficCatBox.setVisible(true); 483 483 for (Cat cat : trafficCats.keySet()) { 484 484 int item = trafficCats.get(cat); 485 if ( dlg.panelMain.mark.getCategory() == cat)485 if (SmedAction.panelMain.mark.getCategory() == cat) 486 486 trafficCatBox.setSelectedIndex(item); 487 487 } 488 488 chLabel.setVisible(true); 489 489 chBox.setVisible(true); 490 } else if ( dlg.panelMain.mark.getObject() == Obj.SISTAW) {490 } else if (SmedAction.panelMain.mark.getObject() == Obj.SISTAW) { 491 491 categoryLabel.setVisible(true); 492 492 warningCatBox.setVisible(true); 493 493 for (Cat cat : warningCats.keySet()) { 494 494 int item = warningCats.get(cat); 495 if ( dlg.panelMain.mark.getCategory() == cat)495 if (SmedAction.panelMain.mark.getCategory() == cat) 496 496 warningCatBox.setSelectedIndex(item); 497 497 } 498 498 chLabel.setVisible(true); 499 499 chBox.setVisible(true); 500 } else if ( dlg.panelMain.mark.getObject() == Obj.OFSPLF) {500 } else if (SmedAction.panelMain.mark.getObject() == Obj.OFSPLF) { 501 501 categoryLabel.setVisible(true); 502 502 platformCatBox.setVisible(true); 503 503 for (Cat cat : platformCats.keySet()) { 504 504 int item = platformCats.get(cat); 505 if ( dlg.panelMain.mark.getCategory() == cat)505 if (SmedAction.panelMain.mark.getCategory() == cat) 506 506 platformCatBox.setSelectedIndex(item); 507 507 } 508 } else if ( dlg.panelMain.mark.getObject() == Obj.PILBOP) {508 } else if (SmedAction.panelMain.mark.getObject() == Obj.PILBOP) { 509 509 categoryLabel.setVisible(true); 510 510 pilotCatBox.setVisible(true); 511 511 for (Cat cat : pilotCats.keySet()) { 512 512 int item = pilotCats.get(cat); 513 if ( dlg.panelMain.mark.getCategory() == cat)513 if (SmedAction.panelMain.mark.getCategory() == cat) 514 514 pilotCatBox.setSelectedIndex(item); 515 515 } 516 516 chLabel.setVisible(true); 517 517 chBox.setVisible(true); 518 } else if ( dlg.panelMain.mark.getObject() == Obj.RSCSTA) {518 } else if (SmedAction.panelMain.mark.getObject() == Obj.RSCSTA) { 519 519 categoryLabel.setVisible(true); 520 520 rescueCatBox.setVisible(true); 521 521 for (Cat cat : rescueCats.keySet()) { 522 522 int item = rescueCats.get(cat); 523 if ( dlg.panelMain.mark.getCategory() == cat)523 if (SmedAction.panelMain.mark.getCategory() == cat) 524 524 rescueCatBox.setSelectedIndex(item); 525 525 } 526 } else if ( dlg.panelMain.mark.getObject() == Obj.RDOSTA) {526 } else if (SmedAction.panelMain.mark.getObject() == Obj.RDOSTA) { 527 527 categoryLabel.setVisible(true); 528 528 radioCatBox.setVisible(true); 529 529 for (Cat cat : radioCats.keySet()) { 530 530 int item = radioCats.get(cat); 531 if ( dlg.panelMain.mark.getCategory() == cat)531 if (SmedAction.panelMain.mark.getCategory() == cat) 532 532 radioCatBox.setSelectedIndex(item); 533 533 } 534 534 chLabel.setVisible(true); 535 535 chBox.setVisible(true); 536 } else if ( dlg.panelMain.mark.getObject() == Obj.RADSTA) {536 } else if (SmedAction.panelMain.mark.getObject() == Obj.RADSTA) { 537 537 categoryLabel.setVisible(true); 538 538 radarCatBox.setVisible(true); 539 539 for (Cat cat : radarCats.keySet()) { 540 540 int item = radarCats.get(cat); 541 if ( dlg.panelMain.mark.getCategory() == cat)541 if (SmedAction.panelMain.mark.getCategory() == cat) 542 542 radarCatBox.setSelectedIndex(item); 543 543 } … … 547 547 for (Obj obj : objects.keySet()) { 548 548 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(); 552 552 } 553 553 -
applications/editors/josm/plugins/smed/src/panels/PanelLit.java
r30737 r30738 21 21 private FocusListener flGroup = new FocusAdapter() { 22 22 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()); 24 24 } 25 25 }; … … 28 28 private FocusListener flPeriod = new FocusAdapter() { 29 29 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()); 31 31 } 32 32 }; … … 35 35 private FocusListener flSequence = new FocusAdapter() { 36 36 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()); 38 38 } 39 39 }; … … 46 46 int idx = visibilities.get(vis); 47 47 if (idx == visibilityBox.getSelectedIndex()) 48 dlg.panelMain.mark.setLightAtt(Att.VIS, 0, vis);48 SmedAction.panelMain.mark.setLightAtt(Att.VIS, 0, vis); 49 49 } 50 50 } … … 54 54 private FocusListener flHeight = new FocusAdapter() { 55 55 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()); 57 57 } 58 58 }; … … 61 61 private FocusListener flRange = new FocusAdapter() { 62 62 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()); 64 64 } 65 65 }; … … 68 68 private FocusListener flOrientation = new FocusAdapter() { 69 69 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()); 71 71 } 72 72 }; … … 75 75 private FocusListener flMultiple = new FocusAdapter() { 76 76 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()); 78 78 } 79 79 }; … … 86 86 int idx = categories.get(lit); 87 87 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, ""); 92 92 multipleBox.setText(""); 93 93 orientationLabel.setVisible(true); … … 95 95 multipleLabel.setVisible(false); 96 96 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, ""); 99 99 orientationBox.setText(""); 100 100 orientationLabel.setVisible(false); … … 103 103 multipleBox.setVisible(true); 104 104 } else { 105 dlg.panelMain.mark.setLightAtt(Att.MLT, 0, "");105 SmedAction.panelMain.mark.setLightAtt(Att.MLT, 0, ""); 106 106 multipleBox.setText(""); 107 dlg.panelMain.mark.setLightAtt(Att.ORT, 0, "");107 SmedAction.panelMain.mark.setLightAtt(Att.ORT, 0, ""); 108 108 orientationBox.setText(""); 109 109 orientationLabel.setVisible(false); … … 122 122 int idx = exhibitions.get(exh); 123 123 if (idx == exhibitionBox.getSelectedIndex()) 124 dlg.panelMain.mark.setLightAtt(Att.EXH, 0, exh);124 SmedAction.panelMain.mark.setLightAtt(Att.EXH, 0, exh); 125 125 } 126 126 } … … 137 137 } else { 138 138 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); 141 141 } 142 142 } … … 285 285 multipleLabel.setVisible(false); 286 286 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)); 296 296 for (Vis vis : visibilities.keySet()) { 297 297 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) 299 299 visibilityBox.setSelectedIndex(item); 300 300 } 301 301 for (Lit lit : categories.keySet()) { 302 302 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) 304 304 categoryBox.setSelectedIndex(item); 305 305 } 306 306 for (Exh exh : exhibitions.keySet()) { 307 307 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) 309 309 exhibitionBox.setSelectedIndex(item); 310 310 } 311 if ( dlg.panelMain.mark.isSectored()) {311 if (SmedAction.panelMain.mark.isSectored()) { 312 312 singleButton.setBorderPainted(false); 313 313 sectorButton.setBorderPainted(true); … … 317 317 sectorButton.setBorderPainted(false); 318 318 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); 321 321 } 322 322 panelCol.syncPanel(); -
applications/editors/josm/plugins/smed/src/panels/PanelMore.java
r30737 r30738 19 19 private FocusListener flInfo = new FocusAdapter() { 20 20 public void focusLost(java.awt.event.FocusEvent e) { 21 dlg.panelMain.mark.setInfo(infoBox.getText());21 SmedAction.panelMain.mark.setInfo(infoBox.getText()); 22 22 } 23 23 }; … … 26 26 private FocusListener flSource = new FocusAdapter() { 27 27 public void focusLost(java.awt.event.FocusEvent e) { 28 dlg.panelMain.mark.setSource(sourceBox.getText());28 SmedAction.panelMain.mark.setSource(sourceBox.getText()); 29 29 } 30 30 }; … … 33 33 private FocusListener flElev = new FocusAdapter() { 34 34 public void focusLost(java.awt.event.FocusEvent e) { 35 dlg.panelMain.mark.setElevation(elevBox.getText());35 SmedAction.panelMain.mark.setElevation(elevBox.getText()); 36 36 } 37 37 }; … … 40 40 private FocusListener flHeight = new FocusAdapter() { 41 41 public void focusLost(java.awt.event.FocusEvent e) { 42 dlg.panelMain.mark.setObjectHeight(heightBox.getText());42 SmedAction.panelMain.mark.setObjectHeight(heightBox.getText()); 43 43 } 44 44 }; … … 50 50 for (Sts sts : statuses.keySet()) { 51 51 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); 54 54 } 55 55 } … … 62 62 for (Cns cns : constructions.keySet()) { 63 63 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); 66 66 } 67 67 } … … 74 74 for (Con con : conspicuities.keySet()) { 75 75 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); 78 78 } 79 79 } … … 86 86 for (Con con : reflectivities.keySet()) { 87 87 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); 90 90 } 91 91 } … … 99 99 public void actionPerformed(java.awt.event.ActionEvent e) { 100 100 if (regionAButton.isSelected()) { 101 dlg.panelMain.mark.setRegion(Reg.A);101 SmedAction.panelMain.mark.setRegion(Reg.A); 102 102 switch (dlg.panelMain.mark.getCategory()) { 103 103 case LAM_PORT: -
applications/editors/josm/plugins/smed/src/panels/PanelPat.java
r30737 r30738 31 31 JRadioButton button = patterns.get(pat); 32 32 if (button.isSelected()) { 33 dlg.panelMain.mark.setPattern(ent, pat);33 SmedAction.panelMain.mark.setPattern(ent, pat); 34 34 button.setBorderPainted(true); 35 35 } else 36 36 button.setBorderPainted(false); 37 37 } 38 switch ( dlg.panelMain.mark.getPattern(ent)) {38 switch (SmedAction.panelMain.mark.getPattern(ent)) { 39 39 case NOPAT: 40 40 panelCol.trimStack(1); … … 74 74 for (Pat pat : patterns.keySet()) { 75 75 JRadioButton button = patterns.get(pat); 76 if ( dlg.panelMain.mark.getPattern(ent) == pat) {76 if (SmedAction.panelMain.mark.getPattern(ent) == pat) { 77 77 button.setBorderPainted(true); 78 78 } else -
applications/editors/josm/plugins/smed/src/panels/PanelPort.java
r30737 r30738 31 31 JRadioButton button = shapes.get(shp); 32 32 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)); 35 35 button.setBorderPainted(true); 36 36 } else 37 37 button.setBorderPainted(false); 38 38 } 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()) { 44 44 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); 47 47 break; 48 48 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); 51 51 break; 52 52 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); 58 58 break; 59 59 } 60 60 } 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()) { 63 63 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); 67 67 break; 68 68 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); 72 72 break; 73 73 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); 78 78 break; 79 79 } 80 80 } 81 dlg.panelMain.panelMore.syncPanel();81 SmedAction.panelMain.panelMore.syncPanel(); 82 82 } 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); 85 85 } 86 86 } … … 104 104 for (Shp shp : shapes.keySet()) { 105 105 JRadioButton button = shapes.get(shp); 106 if ( dlg.panelMain.mark.getShape() == shp) {106 if (SmedAction.panelMain.mark.getShape() == shp) { 107 107 button.setBorderPainted(true); 108 108 } else -
applications/editors/josm/plugins/smed/src/panels/PanelRadar.java
r30737 r30738 35 35 int idx = radioCats.get(cat); 36 36 if (dlg.node != null && (idx == radioCatBox.getSelectedIndex())) { 37 dlg.panelMain.mark.setRadio(cat);37 SmedAction.panelMain.mark.setRadio(cat); 38 38 } 39 39 } … … 52 52 JRadioButton button = rads.get(rtb); 53 53 if (button.isSelected()) { 54 dlg.panelMain.mark.setRadar(rtb);54 SmedAction.panelMain.mark.setRadar(rtb); 55 55 } 56 56 } … … 62 62 private FocusListener flGroup = new FocusAdapter() { 63 63 public void focusLost(java.awt.event.FocusEvent e) { 64 dlg.panelMain.mark.setRaconGroup(groupBox.getText());64 SmedAction.panelMain.mark.setRaconGroup(groupBox.getText()); 65 65 } 66 66 }; … … 69 69 private FocusListener flPeriod = new FocusAdapter() { 70 70 public void focusLost(java.awt.event.FocusEvent e) { 71 dlg.panelMain.mark.setRaconPeriod(periodBox.getText());71 SmedAction.panelMain.mark.setRaconPeriod(periodBox.getText()); 72 72 } 73 73 }; … … 76 76 private FocusListener flSeq = new FocusAdapter() { 77 77 public void focusLost(java.awt.event.FocusEvent e) { 78 dlg.panelMain.mark.setRaconSequence(seqBox.getText());78 SmedAction.panelMain.mark.setRaconSequence(seqBox.getText()); 79 79 } 80 80 }; … … 83 83 private FocusListener flRange = new FocusAdapter() { 84 84 public void focusLost(java.awt.event.FocusEvent e) { 85 dlg.panelMain.mark.setRaconRange(rangeBox.getText());85 SmedAction.panelMain.mark.setRaconRange(rangeBox.getText()); 86 86 } 87 87 }; … … 90 90 private FocusListener flSector1 = new FocusAdapter() { 91 91 public void focusLost(java.awt.event.FocusEvent e) { 92 dlg.panelMain.mark.setRaconSector1(sector1Box.getText());92 SmedAction.panelMain.mark.setRaconSector1(sector1Box.getText()); 93 93 } 94 94 }; … … 97 97 private FocusListener flSector2 = new FocusAdapter() { 98 98 public void focusLost(java.awt.event.FocusEvent e) { 99 dlg.panelMain.mark.setRaconSector2(sector2Box.getText());99 SmedAction.panelMain.mark.setRaconSector2(sector2Box.getText()); 100 100 } 101 101 }; … … 204 204 205 205 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)); 207 207 groupLabel.setVisible(rad); 208 208 groupBox.setVisible(rad); … … 219 219 sectorsLabel.setVisible(rad); 220 220 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); 230 230 aisButton.setBorderPainted(aisButton.isSelected()); 231 radioCatBox.setVisible( dlg.panelMain.mark.getRadio() != Cat.NOROS);231 radioCatBox.setVisible(SmedAction.panelMain.mark.getRadio() != Cat.NOROS); 232 232 } 233 233 -
applications/editors/josm/plugins/smed/src/panels/PanelSaw.java
r30737 r30738 27 27 JRadioButton button = shapes.get(shp); 28 28 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)); 31 31 button.setBorderPainted(true); 32 32 } else 33 33 button.setBorderPainted(false); 34 34 } 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); 40 40 } else { 41 dlg.panelMain.panelChan.topmarkButton.setVisible(false);41 SmedAction.panelMain.panelChan.topmarkButton.setVisible(false); 42 42 } 43 dlg.panelMain.panelMore.syncPanel();43 SmedAction.panelMain.panelMore.syncPanel(); 44 44 } 45 45 }; … … 58 58 for (Shp shp : shapes.keySet()) { 59 59 JRadioButton button = shapes.get(shp); 60 if ( dlg.panelMain.mark.getShape() == shp) {60 if (SmedAction.panelMain.mark.getShape() == shp) { 61 61 button.setBorderPainted(true); 62 62 } else 63 63 button.setBorderPainted(false); 64 64 } 65 dlg.panelMain.mark.testValid();65 SmedAction.panelMain.mark.testValid(); 66 66 } 67 67 -
applications/editors/josm/plugins/smed/src/panels/PanelSectors.java
r30737 r30738 123 123 124 124 public int getRowCount() { 125 if ( dlg.panelMain == null)125 if (SmedAction.panelMain == null) 126 126 return 1; 127 127 else 128 return dlg.panelMain.mark.getSectorCount();128 return SmedAction.panelMain.mark.getSectorCount(); 129 129 } 130 130 … … 152 152 return row; 153 153 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) { 156 156 return Col.UNKCOL; 157 157 } else { 158 return dlg.panelMain.mark.getLightAtt(Att.ALT, row);158 return SmedAction.panelMain.mark.getLightAtt(Att.ALT, row); 159 159 } 160 160 } else { 161 return dlg.panelMain.mark.getLightAtt(Att.COL, row);161 return SmedAction.panelMain.mark.getLightAtt(Att.COL, row); 162 162 } 163 163 case 6: 164 return ( dlg.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR);164 return (SmedAction.panelMain.mark.getLightAtt(Att.LIT, row) == Lit.DIR); 165 165 case 7: 166 166 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); 169 169 else 170 return dlg.panelMain.mark.getLightAtt(col - 1, row);170 return SmedAction.panelMain.mark.getLightAtt(col - 1, row); 171 171 case 12: 172 return visibilities.get( dlg.panelMain.mark.getLightAtt(Att.VIS, row));172 return visibilities.get(SmedAction.panelMain.mark.getLightAtt(Att.VIS, row)); 173 173 case 13: 174 return exhibitions.get( dlg.panelMain.mark.getLightAtt(Att.EXH, row));174 return exhibitions.get(SmedAction.panelMain.mark.getLightAtt(Att.EXH, row)); 175 175 default: 176 return dlg.panelMain.mark.getLightAtt(col - 1, row);176 return SmedAction.panelMain.mark.getLightAtt(col - 1, row); 177 177 } 178 178 } … … 184 184 ImageIcon img = colours.get(colour); 185 185 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); 190 190 } else { 191 dlg.panelMain.mark.setLightAtt(Att.ALT, row, colour);191 SmedAction.panelMain.mark.setLightAtt(Att.ALT, row, colour); 192 192 } 193 193 } else { 194 dlg.panelMain.mark.setLightAtt(Att.COL, row, colour);194 SmedAction.panelMain.mark.setLightAtt(Att.COL, row, colour); 195 195 } 196 196 } … … 200 200 case 10: 201 201 case 11: 202 dlg.panelMain.mark.setLightAtt(col - 1, row, value);202 SmedAction.panelMain.mark.setLightAtt(col - 1, row, value); 203 203 break; 204 204 case 6: 205 205 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, ""); 209 209 } 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, ""); 212 212 } 213 213 break; 214 214 case 7: 215 215 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); 218 218 } else { 219 dlg.panelMain.mark.setLightAtt(col - 1, row, value);219 SmedAction.panelMain.mark.setLightAtt(col - 1, row, value); 220 220 } 221 221 break; … … 224 224 String str = visibilities.get(vis); 225 225 if (str.equals(value)) 226 dlg.panelMain.mark.setLightAtt(Att.VIS, row, vis);226 SmedAction.panelMain.mark.setLightAtt(Att.VIS, row, vis); 227 227 } 228 228 break; … … 231 231 String str = exhibitions.get(exh); 232 232 if (str.equals(value)) 233 dlg.panelMain.mark.setLightAtt(Att.EXH, row, exh);233 SmedAction.panelMain.mark.setLightAtt(Att.EXH, row, exh); 234 234 } 235 235 break; 236 236 default: 237 dlg.panelMain.mark.setLightAtt(col - 1, row, value);237 SmedAction.panelMain.mark.setLightAtt(col - 1, row, value); 238 238 } 239 239 } … … 261 261 } 262 262 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))); 265 265 } 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))); 269 269 return this; 270 270 } … … 276 276 277 277 public void addSector(int idx) { 278 dlg.panelMain.mark.addLight(idx);278 SmedAction.panelMain.mark.addLight(idx); 279 279 table.setSize(860, ((table.getRowCount() * 16) + 28)); 280 280 if (table.getRowCount() > 3) { … … 287 287 public void deleteSector(int idx) { 288 288 if (idx > 0) { 289 dlg.panelMain.mark.delLight(idx);289 SmedAction.panelMain.mark.delLight(idx); 290 290 table.setSize(860, ((table.getRowCount() * 16) + 28)); 291 291 if (table.getRowCount() > 3) { -
applications/editors/josm/plugins/smed/src/panels/PanelSpec.java
r30737 r30738 24 24 int idx = categories.get(cat); 25 25 if (dlg.node != null && (idx == categoryBox.getSelectedIndex())) 26 dlg.panelMain.mark.setCategory(cat);26 SmedAction.panelMain.mark.setCategory(cat); 27 27 } 28 28 } … … 35 35 int idx = moorings.get(cat); 36 36 if (dlg.node != null && (idx == mooringBox.getSelectedIndex())) { 37 dlg.panelMain.mark.setCategory(cat);37 SmedAction.panelMain.mark.setCategory(cat); 38 38 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); 41 41 } else { 42 dlg.panelMain.mark.setObject(Obj.MORFAC);42 SmedAction.panelMain.mark.setObject(Obj.MORFAC); 43 43 if (cat != Cat.MOR_BUOY) 44 dlg.panelMain.mark.setShape(Shp.UNKSHP);44 SmedAction.panelMain.mark.setShape(Shp.UNKSHP); 45 45 } 46 46 } … … 66 66 public ActionListener alShape = new ActionListener() { 67 67 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)) { 69 69 for (Shp shp : shapes.keySet()) { 70 70 JRadioButton button = shapes.get(shp); 71 71 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); 78 78 } 79 79 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); 82 82 } 83 topmarkButton.setVisible( dlg.panelMain.mark.testValid());83 topmarkButton.setVisible(SmedAction.panelMain.mark.testValid()); 84 84 } 85 85 button.setBorderPainted(true); … … 87 87 button.setBorderPainted(false); 88 88 } 89 dlg.panelMain.panelMore.syncPanel();89 SmedAction.panelMain.panelMore.syncPanel(); 90 90 } 91 91 } … … 95 95 public void actionPerformed(java.awt.event.ActionEvent e) { 96 96 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); 100 100 topmarkButton.setBorderPainted(true); 101 101 } 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); 105 105 topmarkButton.setBorderPainted(false); 106 106 } 107 dlg.panelMain.panelTop.syncPanel();107 SmedAction.panelMain.panelTop.syncPanel(); 108 108 } 109 109 }; … … 111 111 private ActionListener alNotice = new ActionListener() { 112 112 public void actionPerformed(java.awt.event.ActionEvent e) { 113 dlg.panelMain.mark.clrMark();113 SmedAction.panelMain.mark.clrMark(); 114 114 if (noticeButton.isSelected()) { 115 dlg.panelMain.mark.setObject(Obj.NOTMRK);115 SmedAction.panelMain.mark.setObject(Obj.NOTMRK); 116 116 noticeButton.setBorderPainted(true); 117 117 } else { 118 dlg.panelMain.mark.setObject(Obj.UNKOBJ);118 SmedAction.panelMain.mark.setObject(Obj.UNKOBJ); 119 119 noticeButton.setBorderPainted(false); 120 120 } 121 dlg.panelMain.syncPanel();121 SmedAction.panelMain.syncPanel(); 122 122 } 123 123 }; … … 125 125 private ActionListener alMooring = new ActionListener() { 126 126 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); 130 130 if (mooringButton.isSelected()) { 131 dlg.panelMain.mark.setObject(Obj.MORFAC);131 SmedAction.panelMain.mark.setObject(Obj.MORFAC); 132 132 categoryBox.setVisible(false); 133 133 mooringBox.setVisible(true); … … 234 234 235 235 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) { 237 237 mooringButton.setBorderPainted(true); 238 238 categoryBox.setVisible(false); … … 248 248 for (Cat cat : moorings.keySet()) { 249 249 int item = moorings.get(cat); 250 if ( dlg.panelMain.mark.getCategory() == cat)250 if (SmedAction.panelMain.mark.getCategory() == cat) 251 251 mooringBox.setSelectedIndex(item); 252 252 } … … 262 262 cairnButton.setEnabled(true); 263 263 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()); 267 267 for (Cat cat : categories.keySet()) { 268 268 int item = categories.get(cat); 269 if ( dlg.panelMain.mark.getCategory() == cat)269 if (SmedAction.panelMain.mark.getCategory() == cat) 270 270 categoryBox.setSelectedIndex(item); 271 271 } … … 273 273 for (Shp shp : shapes.keySet()) { 274 274 JRadioButton button = shapes.get(shp); 275 if ( dlg.panelMain.mark.getShape() == shp) {275 if (SmedAction.panelMain.mark.getShape() == shp) { 276 276 button.setBorderPainted(true); 277 277 } else … … 279 279 } 280 280 noticeButton.setBorderPainted(false); 281 dlg.panelMain.mark.testValid();281 SmedAction.panelMain.mark.testValid(); 282 282 } 283 283 -
applications/editors/josm/plugins/smed/src/panels/PanelStbd.java
r30737 r30738 31 31 JRadioButton button = shapes.get(shp); 32 32 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)); 35 35 button.setBorderPainted(true); 36 36 } else 37 37 button.setBorderPainted(false); 38 38 } 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()) { 44 44 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); 47 47 break; 48 48 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); 51 51 break; 52 52 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); 58 58 break; 59 59 } 60 60 } 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()) { 63 63 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); 67 67 break; 68 68 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); 72 72 break; 73 73 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); 78 78 break; 79 79 } 80 80 } 81 dlg.panelMain.panelMore.syncPanel();81 SmedAction.panelMain.panelMore.syncPanel(); 82 82 } 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); 85 85 } 86 86 } … … 104 104 for (Shp shp : shapes.keySet()) { 105 105 JRadioButton button = shapes.get(shp); 106 if ( dlg.panelMain.mark.getShape() == shp) {106 if (SmedAction.panelMain.mark.getShape() == shp) { 107 107 button.setBorderPainted(true); 108 108 } else -
applications/editors/josm/plugins/smed/src/panels/PanelTop.java
r30737 r30738 38 38 JRadioButton button = tops.get(top); 39 39 if (button.isSelected()) { 40 dlg.panelMain.mark.setTopmark(top);40 SmedAction.panelMain.mark.setTopmark(top); 41 41 button.setBorderPainted(true); 42 42 } else … … 79 79 for (Top top : tops.keySet()) { 80 80 JRadioButton button = tops.get(top); 81 if ( dlg.panelMain.mark.getTopmark() == top) {81 if (SmedAction.panelMain.mark.getTopmark() == top) { 82 82 button.setBorderPainted(true); 83 83 } else -
applications/editors/josm/plugins/smed/src/seamarks/SeaMark.java
r30737 r30738 1361 1361 } 1362 1362 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); 1369 1369 return true; 1370 1370 } 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); 1377 1377 PanelMain.messageBar.setText("Seamark not recognised"); 1378 1378 return false; … … 1398 1398 setSource(""); 1399 1399 setFixme(""); 1400 dlg.panelMain.syncPanel();1400 SmedAction.panelMain.syncPanel(); 1401 1401 repaint(); 1402 1402 } -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/AutoSaveGpsLayerTimerTask.java
r30646 r30738 68 68 // @see LiveGpsLayer 69 69 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 } 73 73 tmpFile.renameTo(file); 74 74 } catch (IOException ioExc) { -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/SurveyorShowAction.java
r30737 r30738 26 26 27 27 import org.openstreetmap.josm.Main; 28 import org.openstreetmap.josm.actions.JosmAction; 28 29 import org.openstreetmap.josm.tools.Shortcut; 29 30 import org.openstreetmap.josm.tools.XmlObjectParser; 30 import org.openstreetmap.josm.actions.JosmAction;31 31 import org.xml.sax.SAXException; 32 32 … … 50 50 } 51 51 52 public void actionPerformed(ActionEvent e) { 52 @Override 53 public void actionPerformed(ActionEvent e) { 53 54 if(surveyorFrame == null) { 54 55 surveyorFrame = new JFrame(); … … 64 65 // zoomout: 65 66 actionMap.put("zoomout", new AbstractAction() { 66 public void actionPerformed(ActionEvent e) { 67 @Override 68 public void actionPerformed(ActionEvent e) { 67 69 if(Main.map != null && Main.map.mapView != null) { 68 70 Main.map.mapView.zoomToFactor(2); … … 73 75 // zoomin: 74 76 actionMap.put("zoomin", new AbstractAction() { 75 public void actionPerformed(ActionEvent e) { 77 @Override 78 public void actionPerformed(ActionEvent e) { 76 79 if(Main.map != null && Main.map.mapView != null) { 77 80 Main.map.mapView.zoomToFactor(1/2); … … 82 85 // autocenter: 83 86 actionMap.put("autocenter", new AbstractAction() { 84 public void actionPerformed(ActionEvent e) { 87 @Override 88 public void actionPerformed(ActionEvent e) { 85 89 // toggle autocenter 86 90 gpsPlugin.setAutoCenter(!gpsPlugin.isAutoCenter()); … … 105 109 106 110 public SurveyorComponent createComponent() { 107 InputStream in = null;108 111 String source = Main.pref.get("surveyor.source"); 109 112 if(source == null || source.length() == 0) { … … 114 117 // </FIXXME> 115 118 } 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); 122 121 } catch (IOException e) { 123 e.printStackTrace();122 Main.error(e); 124 123 JOptionPane.showMessageDialog(Main.parent, tr("Could not read surveyor definition: {0}",source)); 125 124 } catch (SAXException e) { 126 e.printStackTrace();125 Main.error(e); 127 126 JOptionPane.showMessageDialog(Main.parent, tr("Error parsing {0}: {1}", source, e.getMessage())); 128 127 } 129 return component;128 return null; 130 129 } 131 130 -
applications/editors/josm/plugins/surveyor/src/at/dallermassl/josm/plugin/surveyor/util/ResourceLoader.java
r30646 r30738 28 28 * @throws IOException if an error occurs on opening the url, or if the file is not found. 29 29 */ 30 public static InputStream getInputStream(String source) throws IOException { 30 @SuppressWarnings("resource") 31 public static InputStream getInputStream(String source) throws IOException { 31 32 InputStream in = null; 32 33 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 26 26 /** 27 27 * This class manages a list of {@link TagSpecification}s. 28 * 28 * 29 29 * It also provides a method for reading a list of {@link TagSpecification}s from 30 30 * an XML file. 31 * 31 * 32 32 * @author Gubaer 33 33 * … … 63 63 * loads the tag specifications from the resource file given by 64 64 * {@link #RES_NAME_TAG_SPECIFICATIONS}. 65 * 65 * 66 66 * @return the list of {@link TagSpecification}s 67 67 * @throws Exception thrown, if an exception occurs … … 71 71 if (in == null) { 72 72 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= newTagSpecifications();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 } 80 80 } 81 81 … … 97 97 /** 98 98 * loads the tag specifications from a specific reader 99 * 99 * 100 100 * @param in the reader to read from 101 101 * @throws Exception thrown, if an exception occurs … … 156 156 return items; 157 157 } 158 158 159 159 /** 160 160 * replies a list of {@see KeyValuePair}s for all {@see TagSpecification}s and 161 161 * {@see LableSpecification}s. 162 * 162 * 163 163 * @return the list 164 164 */ … … 178 178 /** 179 179 * The SAX handler for reading XML files with tag specifications 180 * 180 * 181 181 * @author gubaer 182 182 * … … 212 212 * parses a string value consisting of 'yes' or 'no' (exactly, case 213 213 * sensitive) 214 * 214 * 215 215 * @param value the string value 216 216 * @return true, if value is <code>yes</code>; false, if value is <code>no</code> … … 228 228 /** 229 229 * handles a start element with name <code>osm-tag-definitions</code> 230 * 230 * 231 231 * @param atts the XML attributes 232 232 * @throws SAXException … … 238 238 /** 239 239 * handles an end element with name <code>osm-tag-specifications</code> 240 * 240 * 241 241 * @throws SAXException 242 242 */ … … 247 247 /** 248 248 * handles a start element with name <code>tag</code> 249 * 249 * 250 250 * @param atts the XML attributes of the element 251 251 * @throws SAXException … … 285 285 /** 286 286 * handles a start element with name <code>label</code> 287 * 287 * 288 288 * @param atts the XML attributes 289 289 * @throws SAXException … … 311 311 /** 312 312 * handles an end element with name <code>label</code> 313 * 313 * 314 314 * @throws SAXException 315 315 */ … … 352 352 class ResourceEntityResolver implements EntityResolver { 353 353 354 public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 354 @Override 355 public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { 355 356 if (systemId != null && systemId.endsWith(DTD)) { 356 357 InputStream stream = TagSpecifications.class.getResourceAsStream("/resources/"+DTD); -
applications/editors/josm/plugins/tracer2/src/org/openstreetmap/josm/plugins/tracer2/preferences/ServerParamList.java
r30737 r30738 1 1 /** 2 2 * Tracer2 - plug-in for JOSM to capture contours 3 * 3 * 4 4 * This program is free software; you can redistribute it and/or modify 5 5 * it under the terms of the GNU General Public License as published by 6 6 * the Free Software Foundation; either version 2 of the License, or 7 7 * (at your option) any later version. 8 * 8 * 9 9 * This program is distributed in the hope that it will be useful, 10 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 12 * GNU General Public License for more details. 13 * 13 * 14 14 * You should have received a copy of the GNU General Public License along 15 15 * with this program; if not, write to the Free Software Foundation, Inc., … … 28 28 import java.util.List; 29 29 30 import org.openstreetmap.josm.Main; 31 30 32 public class ServerParamList { 31 33 ArrayList<ServerParam> m_listServerParam = new ArrayList<>(); 32 34 ServerParam m_oActivParam = null; 33 35 String m_strFilename; 34 36 35 37 public ServerParamList(String filename) { 36 38 this.m_strFilename = filename; … … 41 43 } 42 44 } 43 45 44 46 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"))) { 47 48 StringBuilder oBuilder = new StringBuilder(); 48 49 String strLine; … … 54 55 } 55 56 } 56 oReader.close();57 57 } catch (Exception e) { 58 58 loadDefault(); 59 59 } 60 60 } 61 61 62 62 public void loadDefault() { 63 try {63 try ( 64 64 InputStream oIP = getClass().getResourceAsStream("/resources/serverParam.cfg"); 65 65 BufferedReader oReader = new BufferedReader(new InputStreamReader(oIP)); 66 ) { 66 67 StringBuilder oBuilder = new StringBuilder(); 67 68 String strLine; … … 73 74 } 74 75 } 75 oReader.close();76 76 } 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); 79 78 } 80 79 } 81 80 82 81 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")) { 85 83 for (ServerParam param : m_listServerParam) { 86 84 oWriter.write(param.serialize()); 87 85 } 88 oWriter.close();89 86 } 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); 92 88 } 93 89 } 94 90 95 91 public List<ServerParam> getParamList() { 96 92 return m_listServerParam; 97 93 } 98 94 99 95 public ServerParam getActivParam() { 100 96 return m_oActivParam; … … 105 101 } 106 102 } 107 103 108 104 public List<ServerParam> getEnableParamList() { 109 105 List<ServerParam> listParam = new ArrayList<>(); … … 115 111 return listParam; 116 112 } 117 113 118 114 public void addParam(ServerParam param) { 119 115 m_listServerParam.add(param); 120 116 } 121 117 122 118 public void removeParam(ServerParam param) { 123 119 param.setEnabled(false); 124 120 m_listServerParam.remove(param); 125 121 } 126 127 122 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java
r30724 r30738 13 13 import org.bouncycastle.bcpg.BCPGOutputStream; 14 14 import org.bouncycastle.openpgp.PGPSignature; 15 import org.openstreetmap.josm.Main; 15 16 16 17 public class TrustSignatures { … … 126 127 if (textsigs.containsKey(plain)){ 127 128 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)) { 131 131 aOut.beginClearText(l.get(0).getHashAlgorithm()); 132 132 aOut.write(plain.getBytes(Charset.forName("UTF-8"))); … … 134 134 aOut.endClearText(); 135 135 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 } 139 140 } 140 141 bOut.close();142 aOut.close();143 141 144 142 return baos.toString("UTF-8"); 145 143 146 144 } catch (Exception e) { 147 e.printStackTrace();145 Main.error(e); 148 146 return "Error - read console Output"; 149 147 } … … 153 151 154 152 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)) { 158 155 aOut.beginClearText(sig.getHashAlgorithm()); 159 156 aOut.write(getSigtext(sig).getBytes(Charset.forName("UTF-8"))); … … 161 158 aOut.endClearText(); 162 159 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 } 168 163 169 164 return baos.toString("UTF-8"); 170 165 } catch (Exception e) { 171 e.printStackTrace();166 Main.error(e); 172 167 return "Error - read console Output"; 173 168 } 174 169 } 175 176 170 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java
r30724 r30738 8 8 /** 9 9 * This class is released under GNU general public license 10 * 10 * 11 11 * Description: This class generates random names from syllables, and provides programmer a 12 12 * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names. 13 * 13 * 14 14 * SYLLABLE FILE REQUIREMENTS/FORMAT: 15 15 * 1) all syllables are separated by line break. … … 17 17 * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results. 18 18 * 4) Empty lines are ignored. 19 * 19 * 20 20 * SYLLABLE CLASSIFICATION: 21 21 * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix. … … 23 23 * To declare syllable as a suffix in the file, insert "+" as a first character of the line. 24 24 * everything else is read as a middle part. 25 * 25 * 26 26 * NUMBER OF SYLLABLES: 27 27 * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix. 28 28 * In case of 1 syllable, name will be chosen from amongst the prefixes. 29 29 * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix. 30 * 30 * 31 31 * ASSIGNING RULES: 32 32 * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the 33 33 * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important. 34 * 34 * 35 35 * RULES: 36 36 * 1) +v means that next syllable must definitely start with a vocal. … … 41 41 * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only vocals, which will be detected 42 42 * and RuntimeException will be thrown. 43 * 43 * 44 44 * TO START: 45 45 * Create a new NameGenerator object, provide the syllable file, and create names using compose() method. 46 * 46 * 47 47 * @author Joonas Vali, August 2009. 48 48 * … … 85 85 */ 86 86 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) { 115 108 return s.substring(0,1).toUpperCase().concat(s.substring(1)); 116 109 } 117 110 118 private boolean containsConsFirst(ArrayList<String> array){ 111 private boolean containsConsFirst(ArrayList<String> array) { 119 112 for(String s: array){ 120 113 if(consonantFirst(s)) return true; -
applications/editors/josm/plugins/trustosm/src/tools/NameGenerator.java
r30737 r30738 8 8 /** 9 9 * This class is released under GNU general public license 10 * 10 * 11 11 * Description: This class generates random names from syllables, and provides programmer a 12 12 * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names. 13 * 13 * 14 14 * SYLLABLE FILE REQUIREMENTS/FORMAT: 15 15 * 1) all syllables are separated by line break. … … 17 17 * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results. 18 18 * 4) Empty lines are ignored. 19 * 19 * 20 20 * SYLLABLE CLASSIFICATION: 21 21 * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix. … … 23 23 * To declare syllable as a suffix in the file, insert "+" as a first character of the line. 24 24 * everything else is read as a middle part. 25 * 25 * 26 26 * NUMBER OF SYLLABLES: 27 27 * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix. 28 28 * In case of 1 syllable, name will be chosen from amongst the prefixes. 29 29 * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix. 30 * 30 * 31 31 * ASSIGNING RULES: 32 32 * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the 33 33 * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important. 34 * 34 * 35 35 * RULES: 36 36 * 1) +v means that next syllable must definitely start with a vocal. … … 41 41 * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only vocals, which will be detected 42 42 * and RuntimeException will be thrown. 43 * 43 * 44 44 * TO START: 45 45 * Create a new NameGenerator object, provide the syllable file, and create names using compose() method. 46 * 46 * 47 47 * @author Joonas Vali, August 2009. 48 48 * … … 85 85 */ 86 86 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) { 115 109 return s.substring(0,1).toUpperCase().concat(s.substring(1)); 116 110 } 117 111 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; 121 115 } 122 116 return false; -
applications/editors/josm/plugins/walkingpapers/src/org/openstreetmap/josm/plugins/walkingpapers/WalkingPapersAddLayerAction.java
r29854 r30738 25 25 } 26 26 27 public void actionPerformed(ActionEvent e) { 27 @Override 28 public void actionPerformed(ActionEvent e) { 28 29 String wpid = JOptionPane.showInputDialog(Main.parent, 29 30 tr("Enter a walking-papers.org URL or ID (the bit after the ?id= in the URL)"), … … 51 52 String tile = null; 52 53 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"))) { 55 55 for (String line = r.readLine(); line != null; line = r.readLine()) { 56 56 m = spanPattern.matcher(line); … … 65 65 } 66 66 } 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 } 69 70 } catch (Exception ex) { 70 71 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 25 25 import javax.xml.xpath.XPathFactory; 26 26 27 import org.openstreetmap.josm.Main; 27 28 import org.openstreetmap.josm.data.coor.LatLon; 28 29 import org.openstreetmap.josm.data.osm.OsmPrimitive; … … 116 117 connection.setDoOutput(true); 117 118 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 } 122 122 123 123 final Scanner scanner = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\n"); … … 129 129 status.put(x[0], "1".equals(x[1])); 130 130 } else { 131 System.err.println("Unknown element " + line);131 Main.error("Unknown element " + line); 132 132 } 133 133 }
Note:
See TracChangeset
for help on using the changeset viewer.