Changeset 30724 in osm for applications/editors/josm
- Timestamp:
- 2014-10-16T02:08:59+02:00 (11 years ago)
- Location:
- applications/editors/josm/plugins/trustosm
- Files:
-
- 5 added
- 24 edited
-
.classpath (added)
-
.project (added)
-
.settings (added)
-
.settings/org.eclipse.core.resources.prefs (added)
-
.settings/org.eclipse.jdt.core.prefs (added)
-
src/org/openstreetmap/josm/plugins/trustosm/TrustOSMplugin.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/actions/ExportSigsAction.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/actions/GetMissingDataAction.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/data/TrustNode.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/data/TrustOsmPrimitive.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/data/TrustRelation.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/data/TrustWay.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/DownloadSignedOsmDataTask.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/KeyGenerationTask.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/KeyTreeTableModel.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/JCollapsiblePanel.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/KeySignaturesDialog.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/TrustDialog.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/TrustPreferenceEditor.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/TrustSignaturesDialog.java (modified) (2 diffs)
-
src/org/openstreetmap/josm/plugins/trustosm/io/SigExporter.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/io/SigImporter.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/io/SigReader.java (modified) (3 diffs)
-
src/org/openstreetmap/josm/plugins/trustosm/io/SigWriter.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java (modified) (1 diff)
-
src/org/openstreetmap/josm/plugins/trustosm/util/TrustAnalyzer.java (modified) (2 diffs)
-
src/org/openstreetmap/josm/plugins/trustosm/util/TrustGPG.java (modified) (1 diff)
-
src/tools/NameGenerator.java (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/TrustOSMplugin.java
r29784 r30724 38 38 public class TrustOSMplugin extends Plugin { 39 39 40 static JMenu gpgJMenu; 41 42 private TrustDialog trustDialog; 43 44 /** Use a TrustGPGPreparer to sign or validate signatures */ 45 public static TrustGPG gpg; 46 47 /** A global list with all OSM-Ids and corresponding TrustOSMItems */ 48 public static final Map<String, TrustOsmPrimitive> signedItems = new HashMap<String, TrustOsmPrimitive>(); 49 50 /** 51 * Will be invoked by JOSM to bootstrap the plugin 52 * 53 * @param info information about the plugin and its local installation 54 */ 55 public TrustOSMplugin(PluginInformation info) { 56 // init the plugin 57 super(info); 58 // check if the jarlibs are already extracted or not and extract them if not 59 if (!Main.pref.getBoolean("trustosm.jarLibsExtracted")) { 60 Main.pref.put("trustosm.jarLibsExtracted", extractFiles("trustosm","lib")); 61 Main.pref.put("trustosm.jarLibsExtracted", extractFiles("trustosm","resources")); 62 } 63 64 refreshMenu(); 65 checkForUnrestrictedPolicyFiles(); 66 // register new SigImporter and SigExporter 67 ExtensionFileFilter.importers.add(new SigImporter()); 68 ExtensionFileFilter.exporters.add(new SigExporter()); 69 70 gpg = new TrustGPG(); 71 setSettings(); 72 File gpgDir = new File(getGpgPath()); 73 if (!gpgDir.exists()) 74 gpgDir.mkdirs(); 75 76 } 77 78 public static void checkForUnrestrictedPolicyFiles() { 79 byte[] data = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; 80 81 // create a cipher and attempt to encrypt the data block with our key 82 try{ 83 Cipher c = Cipher.getInstance("AES"); 84 // create a 192 bit secret key from raw bytes 85 86 SecretKey key192 = new SecretKeySpec(new byte[] { 0x00, 0x01, 0x02, 87 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 88 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 89 0x17 }, "AES"); 90 91 // now try encrypting with the larger key 92 93 c.init(Cipher.ENCRYPT_MODE, key192); 94 c.doFinal(data); 95 } catch (Exception e) { 96 //e.printStackTrace(); 97 System.err.println("Warning: It seems that the Unrestricted Policy Files are not available in this JVM. So high level crypto is not allowed. Problems may occure."); 98 //extractFiles("trustosm","jce"); 99 installUnrestrictedPolicyFiles(); 100 } 101 } 102 103 public static boolean installUnrestrictedPolicyFiles() { 104 /* 105 String[] cmd = new String[3]; 106 cmd[0] = "sudo"; 107 cmd[1] = "-S"; 108 cmd[2] = "/tmp/skript.sh"; 109 110 try 111 { 112 Process p = Runtime.getRuntime().exec(cmd); 113 OutputStream os = p.getOutputStream(); 114 Writer writer = new OutputStreamWriter(os); 115 116 JPasswordField passwordField = new JPasswordField(10); 117 JOptionPane.showMessageDialog(null, passwordField, "Enter password", JOptionPane.OK_OPTION); 118 String password = passwordField.getPassword().toString(); 119 120 writer.write(password + "\n"); 121 writer.close(); 122 InputStream in = p.getInputStream(); 123 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 124 String satz = reader.readLine(); 125 while (satz != null) 126 { 127 System.out.println(satz); 128 satz = reader.readLine(); 129 } 130 int rc = p.waitFor(); 131 } 132 catch (Exception e) 133 { 134 System.out.println(e.toString()); 135 } 136 137 /* 138 139 Process p; 140 int exitCode; 141 String stdout,stderr; 142 String sysSecPath = System.getProperty("java.home")+"/lib/security"; 143 File localPolicy = new File(sysSecPath+"/local_policy.jar"); 144 if (!localPolicy.exists()) { 145 System.err.println("No local_policy.jar file found in "+sysSecPath+"\n Is this the right java directory?"); 146 return false; 147 } 148 149 150 String cmd = "sh -c sudo -S mv "+sysSecPath+"/local_policy.jar "+sysSecPath+"/local_policy.jar.restricted"; 151 /* String cmd2 = "sudo -S mv "+sysSecPath+"/US_export_policy.jar "+sysSecPath+"/US_export_policy.jar.restricted"; 152 String cmd3 = "sudo -S cp "+Main.pref.getPluginsDirectory().getPath()+"/trustosm/jce/US_export_policy.jar "+sysSecPath; 153 String cmd4 = "sudo -S cp "+Main.pref.getPluginsDirectory().getPath()+"/trustosm/jce/local_policy.jar "+sysSecPath; 154 155 156 //System.out.println (cmd); 157 158 try 159 { 160 p = Runtime.getRuntime().exec(cmd); 161 } 162 catch(IOException io) 163 { 164 System.err.println ("io Error" + io.getMessage ()); 165 return false; 166 } 167 168 JPasswordField passwordField = new JPasswordField(10); 169 JOptionPane.showMessageDialog(null, passwordField, "Enter password", JOptionPane.OK_OPTION); 170 String password = passwordField.getPassword().toString(); 171 172 if (password != null) 173 { 174 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); 175 try 176 { 177 out.write(password); 178 out.close(); 179 } 180 catch(IOException io) 181 { 182 System.err.println("Exception at write! " + io.getMessage ()); 183 return false; 184 } 185 } 186 187 try 188 { 189 exitCode = p.exitValue (); 190 if (exitCode==0) { 191 System.err.println("Everything seems to be ok."); 192 } else { 193 System.err.println("Exit code was not 0."); 194 StringBuffer buf = new StringBuffer(); 195 InputStream errIn = p.getErrorStream(); 196 int read; 197 while ((read = errIn.read()) != -1) { 198 buf.append(read); 199 } 200 System.err.println(buf.toString()); 201 } 202 } 203 catch (IllegalThreadStateException itse) 204 { 205 return false; 206 } catch (IOException e) { 207 // TODO Auto-generated catch block 208 e.printStackTrace(); 209 } 210 211 */ 212 return false; 213 } 214 215 public static boolean extractFiles(String pluginname, String extractDir) { 216 try { 217 if (extractDir == null) extractDir = "lib"; 218 JarFile jar = new JarFile(Main.pref.getPluginsDirectory().getPath()+"/"+pluginname+".jar"); 219 Enumeration<JarEntry> entries = jar.entries(); 220 InputStream is; 221 FileOutputStream fos; 222 File file; 223 while (entries.hasMoreElements()) { 224 JarEntry entry = entries.nextElement(); 225 String name = entry.getName(); 226 if (name.startsWith(extractDir+"/") && !entry.isDirectory()) { 227 System.out.println(Main.pref.getPluginsDirectory().getPath()+"/"+pluginname+"/"+name); 228 file = new File(Main.pref.getPluginsDirectory().getPath()+"/"+pluginname+"/"+name); 229 file.getParentFile().mkdirs(); 230 is = jar.getInputStream(entry); 231 fos = new FileOutputStream(file); 232 while (is.available() > 0) { // write contents of 'is' to 'fos' 233 fos.write(is.read()); 234 } 235 fos.close(); 236 is.close(); 237 } 238 } 239 return true; 240 241 } catch (IOException e) { 242 e.printStackTrace(); 243 return false; 244 } 245 246 } 247 248 public static void refreshMenu() { 249 MainMenu menu = Main.main.menu; 250 251 if (gpgJMenu == null) { 252 gpgJMenu = menu.addMenu(marktr("GPG"), KeyEvent.VK_B, menu.getDefaultMenuPos(), ht("/Plugin/TrustOSM")); 253 gpgJMenu.add(new JMenuItem(new ExportSigsAction())); 254 } 255 256 } 257 258 public static void setSettings() { 259 Map<String,String> prefs = Main.pref.getAllPrefix("trustosm."); 260 261 // if setting isn't present, we set a default 262 // This makes sense for example when we start the plugin for the first time 263 if (!prefs.containsKey("trustosm.gpg")) Main.pref.put("trustosm.gpg", "gpg"); 264 if (!prefs.containsKey("trustosm.gpg.separateHomedir")) Main.pref.put("trustosm.gpg.separateHomedir", true); 265 } 266 267 268 @Override 269 public PreferenceSetting getPreferenceSetting() { 270 return new TrustPreferenceEditor(); 271 } 272 273 @Override 274 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 275 if (oldFrame==null && newFrame!=null) { 276 trustDialog = new TrustDialog(); 277 newFrame.addToggleDialog(trustDialog); 278 } 279 } 280 281 public static String getGpgPath() { 282 return Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/"; 283 } 284 40 static JMenu gpgJMenu; 41 42 private TrustDialog trustDialog; 43 44 /** Use a TrustGPGPreparer to sign or validate signatures */ 45 public static TrustGPG gpg; 46 47 /** A global list with all OSM-Ids and corresponding TrustOSMItems */ 48 public static final Map<String, TrustOsmPrimitive> signedItems = new HashMap<>(); 49 50 /** 51 * Will be invoked by JOSM to bootstrap the plugin 52 * 53 * @param info information about the plugin and its local installation 54 */ 55 public TrustOSMplugin(PluginInformation info) { 56 // init the plugin 57 super(info); 58 // check if the jarlibs are already extracted or not and extract them if not 59 if (!Main.pref.getBoolean("trustosm.jarLibsExtracted")) { 60 Main.pref.put("trustosm.jarLibsExtracted", extractFiles("trustosm","lib")); 61 Main.pref.put("trustosm.jarLibsExtracted", extractFiles("trustosm","resources")); 62 } 63 64 refreshMenu(); 65 checkForUnrestrictedPolicyFiles(); 66 // register new SigImporter and SigExporter 67 ExtensionFileFilter.importers.add(new SigImporter()); 68 ExtensionFileFilter.exporters.add(new SigExporter()); 69 70 gpg = new TrustGPG(); 71 setSettings(); 72 File gpgDir = new File(getGpgPath()); 73 if (!gpgDir.exists()) 74 gpgDir.mkdirs(); 75 76 } 77 78 public static void checkForUnrestrictedPolicyFiles() { 79 byte[] data = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; 80 81 // create a cipher and attempt to encrypt the data block with our key 82 try{ 83 Cipher c = Cipher.getInstance("AES"); 84 // create a 192 bit secret key from raw bytes 85 86 SecretKey key192 = new SecretKeySpec(new byte[] { 0x00, 0x01, 0x02, 87 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 88 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 89 0x17 }, "AES"); 90 91 // now try encrypting with the larger key 92 93 c.init(Cipher.ENCRYPT_MODE, key192); 94 c.doFinal(data); 95 } catch (Exception e) { 96 //e.printStackTrace(); 97 System.err.println("Warning: It seems that the Unrestricted Policy Files are not available in this JVM. So high level crypto is not allowed. Problems may occure."); 98 //extractFiles("trustosm","jce"); 99 installUnrestrictedPolicyFiles(); 100 } 101 } 102 103 public static boolean installUnrestrictedPolicyFiles() { 104 /* 105 String[] cmd = new String[3]; 106 cmd[0] = "sudo"; 107 cmd[1] = "-S"; 108 cmd[2] = "/tmp/skript.sh"; 109 110 try 111 { 112 Process p = Runtime.getRuntime().exec(cmd); 113 OutputStream os = p.getOutputStream(); 114 Writer writer = new OutputStreamWriter(os); 115 116 JPasswordField passwordField = new JPasswordField(10); 117 JOptionPane.showMessageDialog(null, passwordField, "Enter password", JOptionPane.OK_OPTION); 118 String password = passwordField.getPassword().toString(); 119 120 writer.write(password + "\n"); 121 writer.close(); 122 InputStream in = p.getInputStream(); 123 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 124 String satz = reader.readLine(); 125 while (satz != null) 126 { 127 System.out.println(satz); 128 satz = reader.readLine(); 129 } 130 int rc = p.waitFor(); 131 } 132 catch (Exception e) 133 { 134 System.out.println(e.toString()); 135 } 136 137 /* 138 139 Process p; 140 int exitCode; 141 String stdout,stderr; 142 String sysSecPath = System.getProperty("java.home")+"/lib/security"; 143 File localPolicy = new File(sysSecPath+"/local_policy.jar"); 144 if (!localPolicy.exists()) { 145 System.err.println("No local_policy.jar file found in "+sysSecPath+"\n Is this the right java directory?"); 146 return false; 147 } 148 149 150 String cmd = "sh -c sudo -S mv "+sysSecPath+"/local_policy.jar "+sysSecPath+"/local_policy.jar.restricted"; 151 /* String cmd2 = "sudo -S mv "+sysSecPath+"/US_export_policy.jar "+sysSecPath+"/US_export_policy.jar.restricted"; 152 String cmd3 = "sudo -S cp "+Main.pref.getPluginsDirectory().getPath()+"/trustosm/jce/US_export_policy.jar "+sysSecPath; 153 String cmd4 = "sudo -S cp "+Main.pref.getPluginsDirectory().getPath()+"/trustosm/jce/local_policy.jar "+sysSecPath; 154 155 156 //System.out.println (cmd); 157 158 try 159 { 160 p = Runtime.getRuntime().exec(cmd); 161 } 162 catch(IOException io) 163 { 164 System.err.println ("io Error" + io.getMessage ()); 165 return false; 166 } 167 168 JPasswordField passwordField = new JPasswordField(10); 169 JOptionPane.showMessageDialog(null, passwordField, "Enter password", JOptionPane.OK_OPTION); 170 String password = passwordField.getPassword().toString(); 171 172 if (password != null) 173 { 174 BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); 175 try 176 { 177 out.write(password); 178 out.close(); 179 } 180 catch(IOException io) 181 { 182 System.err.println("Exception at write! " + io.getMessage ()); 183 return false; 184 } 185 } 186 187 try 188 { 189 exitCode = p.exitValue (); 190 if (exitCode==0) { 191 System.err.println("Everything seems to be ok."); 192 } else { 193 System.err.println("Exit code was not 0."); 194 StringBuffer buf = new StringBuffer(); 195 InputStream errIn = p.getErrorStream(); 196 int read; 197 while ((read = errIn.read()) != -1) { 198 buf.append(read); 199 } 200 System.err.println(buf.toString()); 201 } 202 } 203 catch (IllegalThreadStateException itse) 204 { 205 return false; 206 } catch (IOException e) { 207 // TODO Auto-generated catch block 208 e.printStackTrace(); 209 } 210 211 */ 212 return false; 213 } 214 215 public static boolean extractFiles(String pluginname, String extractDir) { 216 if (extractDir == null) extractDir = "lib"; 217 String path = Main.pref.getPluginsDirectory().getPath(); 218 try (JarFile jar = new JarFile(path+"/"+pluginname+".jar")) { 219 Enumeration<JarEntry> entries = jar.entries(); 220 InputStream is; 221 FileOutputStream fos; 222 File file; 223 while (entries.hasMoreElements()) { 224 JarEntry entry = entries.nextElement(); 225 String name = entry.getName(); 226 if (name.startsWith(extractDir+"/") && !entry.isDirectory()) { 227 file = new File(path+"/"+pluginname+"/"+name); 228 file.getParentFile().mkdirs(); 229 is = jar.getInputStream(entry); 230 fos = new FileOutputStream(file); 231 while (is.available() > 0) { // write contents of 'is' to 'fos' 232 fos.write(is.read()); 233 } 234 fos.close(); 235 is.close(); 236 } 237 } 238 return true; 239 240 } catch (IOException e) { 241 e.printStackTrace(); 242 return false; 243 } 244 } 245 246 public static void refreshMenu() { 247 MainMenu menu = Main.main.menu; 248 249 if (gpgJMenu == null) { 250 gpgJMenu = menu.addMenu(marktr("GPG"), KeyEvent.VK_B, menu.getDefaultMenuPos(), ht("/Plugin/TrustOSM")); 251 gpgJMenu.add(new JMenuItem(new ExportSigsAction())); 252 } 253 254 } 255 256 public static void setSettings() { 257 Map<String,String> prefs = Main.pref.getAllPrefix("trustosm."); 258 259 // if setting isn't present, we set a default 260 // This makes sense for example when we start the plugin for the first time 261 if (!prefs.containsKey("trustosm.gpg")) Main.pref.put("trustosm.gpg", "gpg"); 262 if (!prefs.containsKey("trustosm.gpg.separateHomedir")) Main.pref.put("trustosm.gpg.separateHomedir", true); 263 } 264 265 266 @Override 267 public PreferenceSetting getPreferenceSetting() { 268 return new TrustPreferenceEditor(); 269 } 270 271 @Override 272 public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) { 273 if (oldFrame==null && newFrame!=null) { 274 trustDialog = new TrustDialog(); 275 newFrame.addToggleDialog(trustDialog); 276 } 277 } 278 279 public static String getGpgPath() { 280 return Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/"; 281 } 285 282 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/actions/ExportSigsAction.java
r27852 r30724 15 15 public class ExportSigsAction extends DiskAccessAction { 16 16 17 public ExportSigsAction() {18 super(tr("Export sigs..."), "exportsigs", tr("Export all signatures to XML file."),19 Shortcut.registerShortcut("file:exportsigs", tr("Export sigs to XML..."), KeyEvent.VK_X, Shortcut.ALT_CTRL));20 }17 public ExportSigsAction() { 18 super(tr("Export sigs..."), "exportsigs", tr("Export all signatures to XML file."), 19 Shortcut.registerShortcut("file:exportsigs", tr("Export sigs to XML..."), KeyEvent.VK_X, Shortcut.ALT_CTRL)); 20 } 21 21 22 public ExportSigsAction(String name, String iconName, String tooltip, Shortcut shortcut) {23 super(name, iconName, tooltip, shortcut);24 }22 public ExportSigsAction(String name, String iconName, String tooltip, Shortcut shortcut) { 23 super(name, iconName, tooltip, shortcut); 24 } 25 25 26 @Override27 public void actionPerformed(ActionEvent e) {28 if (!isEnabled())29 return;30 doSave();31 }26 @Override 27 public void actionPerformed(ActionEvent e) { 28 if (!isEnabled()) 29 return; 30 doSave(); 31 } 32 32 33 public boolean doSave() {34 File f = createAndOpenSaveFileChooser(tr("Save Signatures file"), "tosm");35 if (f == null)36 return false;37 SigExporter exporter = new SigExporter();38 try {39 exporter.exportData(f, null);40 } catch (IOException e) {41 e.printStackTrace();42 return false;43 }44 return true;45 }33 public boolean doSave() { 34 File f = createAndOpenSaveFileChooser(tr("Save Signatures file"), "tosm"); 35 if (f == null) 36 return false; 37 SigExporter exporter = new SigExporter(); 38 try { 39 exporter.exportData(f, null); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 return false; 43 } 44 return true; 45 } 46 46 47 47 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/actions/GetMissingDataAction.java
r27852 r30724 21 21 public class GetMissingDataAction extends JosmAction { 22 22 23 public GetMissingDataAction() {24 super(tr("Download OSM"),"getmissing",tr("Get all referenced but not actually present OSM objects from OSM server."),25 Shortcut.registerShortcut("gpg:download", tr("Download referenced osm objects..."), KeyEvent.VK_T, Shortcut.CTRL),true);26 }23 public GetMissingDataAction() { 24 super(tr("Download OSM"),"getmissing",tr("Get all referenced but not actually present OSM objects from OSM server."), 25 Shortcut.registerShortcut("gpg:download", tr("Download referenced osm objects..."), KeyEvent.VK_T, Shortcut.CTRL),true); 26 } 27 27 28 @Override29 public void actionPerformed(ActionEvent arg0) {30 if (!isEnabled())31 return;32 downloadMissing();33 }28 @Override 29 public void actionPerformed(ActionEvent arg0) { 30 if (!isEnabled()) 31 return; 32 downloadMissing(); 33 } 34 34 35 public boolean downloadMissing() {36 Collection<OsmPrimitive> missingData = new HashSet<OsmPrimitive>();37 Map<String,TrustOsmPrimitive> trustitems = TrustOSMplugin.signedItems;38 getMissing(trustitems, missingData);35 public boolean downloadMissing() { 36 Collection<OsmPrimitive> missingData = new HashSet<>(); 37 Map<String,TrustOsmPrimitive> trustitems = TrustOSMplugin.signedItems; 38 getMissing(trustitems, missingData); 39 39 40 int missingCount = missingData.size();41 int itemCount = trustitems.size();42 if (missingCount == 0) {43 JOptionPane.showMessageDialog(Main.parent, tr("{0} Signatures loaded. All referenced OSM objects found.",itemCount));44 } else {45 int n = JOptionPane.showOptionDialog(Main.parent, tr("{0} of {1} OSM objects are referenced but not there.\nDo you want to load them from OSM-Server?",missingCount,itemCount), tr("Load objects from server"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);40 int missingCount = missingData.size(); 41 int itemCount = trustitems.size(); 42 if (missingCount == 0) { 43 JOptionPane.showMessageDialog(Main.parent, tr("{0} Signatures loaded. All referenced OSM objects found.",itemCount)); 44 } else { 45 int n = JOptionPane.showOptionDialog(Main.parent, tr("{0} of {1} OSM objects are referenced but not there.\nDo you want to load them from OSM-Server?",missingCount,itemCount), tr("Load objects from server"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 46 46 47 if (n == JOptionPane.YES_OPTION) {48 Main.worker.submit(new DownloadSignedOsmDataTask(missingData, Main.main.getEditLayer()));49 return true;50 }51 }47 if (n == JOptionPane.YES_OPTION) { 48 Main.worker.submit(new DownloadSignedOsmDataTask(missingData, Main.main.getEditLayer())); 49 return true; 50 } 51 } 52 52 53 return false;54 }53 return false; 54 } 55 55 56 public void getMissing(Map<String,TrustOsmPrimitive> trustitems, Collection<OsmPrimitive> missingData) {57 Collection<OsmPrimitive> presentData = Main.main.getCurrentDataSet().allPrimitives();58 for (TrustOsmPrimitive t : trustitems.values()) {59 OsmPrimitive osm = t.getOsmPrimitive();60 if (!presentData.contains(osm))61 missingData.add(osm);62 }63 }56 public void getMissing(Map<String,TrustOsmPrimitive> trustitems, Collection<OsmPrimitive> missingData) { 57 Collection<OsmPrimitive> presentData = Main.main.getCurrentDataSet().allPrimitives(); 58 for (TrustOsmPrimitive t : trustitems.values()) { 59 OsmPrimitive osm = t.getOsmPrimitive(); 60 if (!presentData.contains(osm)) 61 missingData.add(osm); 62 } 63 } 64 64 65 65 -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustNode.java
r26053 r30724 13 13 14 14 15 public static Node generateNodeFromSigtext(String sigtext) {16 Pattern p = Pattern.compile("^(\\d*)\\((\\d*\\.?\\d*),(\\d*\\.?\\d*)\\)");17 Matcher m = p.matcher(sigtext);18 if (m.matches()) {19 Node node = new Node(Long.parseLong(m.group(1)));20 node.setCoor(new LatLon(Double.parseDouble(m.group(2)),Double.parseDouble(m.group(3))));21 return node;22 }23 return null;24 }15 public static Node generateNodeFromSigtext(String sigtext) { 16 Pattern p = Pattern.compile("^(\\d*)\\((\\d*\\.?\\d*),(\\d*\\.?\\d*)\\)"); 17 Matcher m = p.matcher(sigtext); 18 if (m.matches()) { 19 Node node = new Node(Long.parseLong(m.group(1))); 20 node.setCoor(new LatLon(Double.parseDouble(m.group(2)),Double.parseDouble(m.group(3)))); 21 return node; 22 } 23 return null; 24 } 25 25 26 public static String generateNodeSigtext(Node node) {27 LatLon point = node.getCoor();28 String sigtext = node.getUniqueId() + "(";29 sigtext += point.latToString(CoordinateFormat.DECIMAL_DEGREES) + ",";30 sigtext += point.lonToString(CoordinateFormat.DECIMAL_DEGREES) + ")";31 return sigtext;32 }26 public static String generateNodeSigtext(Node node) { 27 LatLon point = node.getCoor(); 28 String sigtext = node.getUniqueId() + "("; 29 sigtext += point.latToString(CoordinateFormat.DECIMAL_DEGREES) + ","; 30 sigtext += point.lonToString(CoordinateFormat.DECIMAL_DEGREES) + ")"; 31 return sigtext; 32 } 33 33 34 private TrustSignatures ratings;34 private TrustSignatures ratings; 35 35 36 public TrustNode(Node osmItem) {37 super(osmItem);38 }36 public TrustNode(Node osmItem) { 37 super(osmItem); 38 } 39 39 40 @Override41 public void setOsmPrimitive(OsmPrimitive osmItem) {42 if(osmItem instanceof Node) {43 osm = osmItem;44 } else {45 System.err.println("Error while creating TrustNode: OsmPrimitive "+osmItem.getUniqueId()+" is not a Node!");46 }47 }40 @Override 41 public void setOsmPrimitive(OsmPrimitive osmItem) { 42 if(osmItem instanceof Node) { 43 osm = osmItem; 44 } else { 45 System.err.println("Error while creating TrustNode: OsmPrimitive "+osmItem.getUniqueId()+" is not a Node!"); 46 } 47 } 48 48 49 public void storeNodeSig(PGPSignature sig) {50 if (ratings == null) {51 ratings = new TrustSignatures(sig, TrustNode.generateNodeSigtext((Node) osm), TrustSignatures.SIG_VALID);52 } else {53 ratings.addSignature(sig, TrustNode.generateNodeSigtext((Node) osm));54 }55 }49 public void storeNodeSig(PGPSignature sig) { 50 if (ratings == null) { 51 ratings = new TrustSignatures(sig, TrustNode.generateNodeSigtext((Node) osm), TrustSignatures.SIG_VALID); 52 } else { 53 ratings.addSignature(sig, TrustNode.generateNodeSigtext((Node) osm)); 54 } 55 } 56 56 57 public void setNodeRatings(TrustSignatures ratings) {58 this.ratings =ratings;59 }57 public void setNodeRatings(TrustSignatures ratings) { 58 this.ratings =ratings; 59 } 60 60 61 public TrustSignatures getNodeSigs() {62 return ratings;63 }61 public TrustSignatures getNodeSigs() { 62 return ratings; 63 } 64 64 65 65 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustOsmPrimitive.java
r26053 r30724 13 13 abstract public class TrustOsmPrimitive { 14 14 15 public static String createUniqueObjectIdentifier(OsmPrimitive osm) {16 String id = "";17 if(osm instanceof Node) {18 id = "n";19 } else if(osm instanceof Way) {20 id = "w";21 } else if(osm instanceof Relation) {22 id = "r";23 }24 id += osm.getUniqueId();25 return id;26 }15 public static String createUniqueObjectIdentifier(OsmPrimitive osm) { 16 String id = ""; 17 if(osm instanceof Node) { 18 id = "n"; 19 } else if(osm instanceof Way) { 20 id = "w"; 21 } else if(osm instanceof Relation) { 22 id = "r"; 23 } 24 id += osm.getUniqueId(); 25 return id; 26 } 27 27 28 public static OsmPrimitive createOsmPrimitiveFromUniqueObjectIdentifier(String oid) {29 char type = oid.charAt(0);30 long id = Long.parseLong(oid.substring(1));31 switch (type) {32 case 'n': return new Node(id);33 case 'w': return new Way(id);34 case 'r': return new Relation(id);35 }36 return null;37 }28 public static OsmPrimitive createOsmPrimitiveFromUniqueObjectIdentifier(String oid) { 29 char type = oid.charAt(0); 30 long id = Long.parseLong(oid.substring(1)); 31 switch (type) { 32 case 'n': return new Node(id); 33 case 'w': return new Way(id); 34 case 'r': return new Relation(id); 35 } 36 return null; 37 } 38 38 39 public static TrustOsmPrimitive createTrustOsmPrimitive(OsmPrimitive osm) {40 if(osm instanceof Node) {41 return new TrustNode((Node) osm);42 } else if(osm instanceof Way) {43 return new TrustWay(osm);44 } else if(osm instanceof Relation) {45 return new TrustRelation(osm);46 }47 return null;48 }39 public static TrustOsmPrimitive createTrustOsmPrimitive(OsmPrimitive osm) { 40 if(osm instanceof Node) { 41 return new TrustNode((Node) osm); 42 } else if(osm instanceof Way) { 43 return new TrustWay(osm); 44 } else if(osm instanceof Relation) { 45 return new TrustRelation(osm); 46 } 47 return null; 48 } 49 49 50 protected OsmPrimitive osm;51 private final Map<String, TrustSignatures> keySig = new HashMap<String, TrustSignatures>();50 protected OsmPrimitive osm; 51 private final Map<String, TrustSignatures> keySig = new HashMap<>(); 52 52 53 public TrustOsmPrimitive(OsmPrimitive osmItem) {54 setOsmPrimitive(osmItem);55 }53 public TrustOsmPrimitive(OsmPrimitive osmItem) { 54 setOsmPrimitive(osmItem); 55 } 56 56 57 public OsmPrimitive getOsmPrimitive() {58 return osm;59 }57 public OsmPrimitive getOsmPrimitive() { 58 return osm; 59 } 60 60 61 public abstract void setOsmPrimitive(OsmPrimitive osmItem);61 public abstract void setOsmPrimitive(OsmPrimitive osmItem); 62 62 63 63 64 public static String[] generateTagsFromSigtext(String sigtext) {65 String[] keyValue = sigtext.substring(sigtext.indexOf('\n')+1).split("=");66 return keyValue;67 }64 public static String[] generateTagsFromSigtext(String sigtext) { 65 String[] keyValue = sigtext.substring(sigtext.indexOf('\n')+1).split("="); 66 return keyValue; 67 } 68 68 69 public static String generateTagSigtext(OsmPrimitive osm, String key) {70 String sigtext = "ID=" + osm.getUniqueId() + "\n";71 sigtext += key + "=" + osm.get(key);72 return sigtext;73 }69 public static String generateTagSigtext(OsmPrimitive osm, String key) { 70 String sigtext = "ID=" + osm.getUniqueId() + "\n"; 71 sigtext += key + "=" + osm.get(key); 72 return sigtext; 73 } 74 74 75 public void storeTagSig(String key, PGPSignature sig) {76 if (keySig.containsKey(key)) {77 keySig.get(key).addSignature(sig, TrustOsmPrimitive.generateTagSigtext(osm, key));78 return;79 } else if (osm.keySet().contains(key)) {80 keySig.put(key, new TrustSignatures(sig, TrustOsmPrimitive.generateTagSigtext(osm, key), TrustSignatures.SIG_VALID));81 }82 }75 public void storeTagSig(String key, PGPSignature sig) { 76 if (keySig.containsKey(key)) { 77 keySig.get(key).addSignature(sig, TrustOsmPrimitive.generateTagSigtext(osm, key)); 78 return; 79 } else if (osm.keySet().contains(key)) { 80 keySig.put(key, new TrustSignatures(sig, TrustOsmPrimitive.generateTagSigtext(osm, key), TrustSignatures.SIG_VALID)); 81 } 82 } 83 83 84 public void setTagRatings(String key, TrustSignatures tsigs) {85 keySig.put(key, tsigs);86 }84 public void setTagRatings(String key, TrustSignatures tsigs) { 85 keySig.put(key, tsigs); 86 } 87 87 88 /*89 public Map<Node, TrustSignatures> getGeomSigs() {90 return geomSig;91 }88 /* 89 public Map<Node, TrustSignatures> getGeomSigs() { 90 return geomSig; 91 } 92 92 93 public TrustSignatures getSigsOnNode(Node node) {94 return geomSig.get(node);95 }*/93 public TrustSignatures getSigsOnNode(Node node) { 94 return geomSig.get(node); 95 }*/ 96 96 97 public Set<String> getSignedKeys() {98 return keySig.keySet();99 }97 public Set<String> getSignedKeys() { 98 return keySig.keySet(); 99 } 100 100 101 public Map<String, TrustSignatures> getTagSigs() {102 return keySig;103 }101 public Map<String, TrustSignatures> getTagSigs() { 102 return keySig; 103 } 104 104 105 public TrustSignatures getSigsOnKey(String key) {106 return keySig.get(key);107 }105 public TrustSignatures getSigsOnKey(String key) { 106 return keySig.get(key); 107 } 108 108 109 public void updateTagSigStatus(String key, byte status) {110 if (keySig.containsKey(key)) {111 keySig.get(key).setStatus(status);112 } else if (osm.keySet().contains(key)) {113 TrustSignatures tsigs = new TrustSignatures();114 tsigs.setStatus(status);115 keySig.put(key, tsigs);116 }117 }118 /*119 public void updateNodeSigStatus(Node node, byte status) {120 if (geomSig.containsKey(node)) {121 geomSig.get(node).setStatus(status);122 } else {123 TrustSignatures tsigs = new TrustSignatures();124 tsigs.setStatus(status);125 geomSig.put(node, tsigs);126 }127 }*/109 public void updateTagSigStatus(String key, byte status) { 110 if (keySig.containsKey(key)) { 111 keySig.get(key).setStatus(status); 112 } else if (osm.keySet().contains(key)) { 113 TrustSignatures tsigs = new TrustSignatures(); 114 tsigs.setStatus(status); 115 keySig.put(key, tsigs); 116 } 117 } 118 /* 119 public void updateNodeSigStatus(Node node, byte status) { 120 if (geomSig.containsKey(node)) { 121 geomSig.get(node).setStatus(status); 122 } else { 123 TrustSignatures tsigs = new TrustSignatures(); 124 tsigs.setStatus(status); 125 geomSig.put(node, tsigs); 126 } 127 }*/ 128 128 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustRelation.java
r26053 r30724 15 15 16 16 17 public static RelationMember generateRelationMemberFromSigtext(String sigtext) {18 Pattern p = Pattern.compile("^RelID=(\\w*)\n(\\d*),(.*)");19 Matcher m = p.matcher(sigtext);20 if (m.matches()) {21 OsmPrimitive osm = createOsmPrimitiveFromUniqueObjectIdentifier(m.group(2));22 return new RelationMember(m.group(3),osm);23 }24 return null;25 }17 public static RelationMember generateRelationMemberFromSigtext(String sigtext) { 18 Pattern p = Pattern.compile("^RelID=(\\w*)\n(\\d*),(.*)"); 19 Matcher m = p.matcher(sigtext); 20 if (m.matches()) { 21 OsmPrimitive osm = createOsmPrimitiveFromUniqueObjectIdentifier(m.group(2)); 22 return new RelationMember(m.group(3),osm); 23 } 24 return null; 25 } 26 26 27 public static String generateRelationMemberSigtext(TrustRelation trust, String memID) {28 Relation r = (Relation)trust.getOsmPrimitive();29 List<RelationMember> members = r.getMembers();30 RelationMember member = null;31 for (RelationMember m : members) {32 if (TrustOsmPrimitive.createUniqueObjectIdentifier(m.getMember()).equals(memID)) {33 member = m;34 break;35 }36 }37 if (member == null) return "";38 String sigtext = "RelID=" + r.getUniqueId() + "\n";39 sigtext += TrustOsmPrimitive.createUniqueObjectIdentifier(member.getMember())+","+member.getRole();40 return sigtext;41 }27 public static String generateRelationMemberSigtext(TrustRelation trust, String memID) { 28 Relation r = (Relation)trust.getOsmPrimitive(); 29 List<RelationMember> members = r.getMembers(); 30 RelationMember member = null; 31 for (RelationMember m : members) { 32 if (TrustOsmPrimitive.createUniqueObjectIdentifier(m.getMember()).equals(memID)) { 33 member = m; 34 break; 35 } 36 } 37 if (member == null) return ""; 38 String sigtext = "RelID=" + r.getUniqueId() + "\n"; 39 sigtext += TrustOsmPrimitive.createUniqueObjectIdentifier(member.getMember())+","+member.getRole(); 40 return sigtext; 41 } 42 42 43 private final Map<String, TrustSignatures> memberSig = new HashMap<String, TrustSignatures>();43 private final Map<String, TrustSignatures> memberSig = new HashMap<>(); 44 44 45 public TrustRelation(OsmPrimitive osmItem) {46 super(osmItem);47 }45 public TrustRelation(OsmPrimitive osmItem) { 46 super(osmItem); 47 } 48 48 49 @Override50 public void setOsmPrimitive(OsmPrimitive osmItem) {51 if(osmItem instanceof Relation) {52 osm = osmItem;53 } else {54 System.err.println("Error while creating TrustRelation: OsmPrimitive "+osmItem.getUniqueId()+" is not a Relation!");55 }56 }49 @Override 50 public void setOsmPrimitive(OsmPrimitive osmItem) { 51 if(osmItem instanceof Relation) { 52 osm = osmItem; 53 } else { 54 System.err.println("Error while creating TrustRelation: OsmPrimitive "+osmItem.getUniqueId()+" is not a Relation!"); 55 } 56 } 57 57 58 58 59 public void storeMemberSig(String memID, PGPSignature sig) {60 if (memberSig.containsKey(memID)) {61 memberSig.get(memID).addSignature(sig, TrustRelation.generateRelationMemberSigtext(this, memID));62 return;63 } else {64 memberSig.put(memID, new TrustSignatures(sig, TrustRelation.generateRelationMemberSigtext(this, memID), TrustSignatures.SIG_VALID));65 }66 }59 public void storeMemberSig(String memID, PGPSignature sig) { 60 if (memberSig.containsKey(memID)) { 61 memberSig.get(memID).addSignature(sig, TrustRelation.generateRelationMemberSigtext(this, memID)); 62 return; 63 } else { 64 memberSig.put(memID, new TrustSignatures(sig, TrustRelation.generateRelationMemberSigtext(this, memID), TrustSignatures.SIG_VALID)); 65 } 66 } 67 67 68 public void setMemberRating(String memID, TrustSignatures tsigs) {69 memberSig.put(memID, tsigs);70 }68 public void setMemberRating(String memID, TrustSignatures tsigs) { 69 memberSig.put(memID, tsigs); 70 } 71 71 72 public Map<String, TrustSignatures> getMemberSigs() {73 return memberSig;74 }72 public Map<String, TrustSignatures> getMemberSigs() { 73 return memberSig; 74 } 75 75 76 76 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustSignatures.java
r25269 r30724 16 16 public class TrustSignatures { 17 17 18 public final static byte SIG_UNKNOWN = 0;19 public final static byte SIG_VALID = 1;20 public final static byte SIG_BROKEN = -1;21 public final static byte ITEM_REMOVED = -2;18 public final static byte SIG_UNKNOWN = 0; 19 public final static byte SIG_VALID = 1; 20 public final static byte SIG_BROKEN = -1; 21 public final static byte ITEM_REMOVED = -2; 22 22 23 //private final Vector<PGPSignature> signatures = new Vector<PGPSignature>();24 //private final HashMap<PGPSignature, String> signatureTextMap = new HashMap<PGPSignature, String>();25 private final Map<String, List<PGPSignature>> textsigs = new HashMap<String, List<PGPSignature>>();26 private byte status;27 private double reputation;23 //private final Vector<PGPSignature> signatures = new Vector<PGPSignature>(); 24 // private final HashMap<PGPSignature, String> signatureTextMap = new HashMap<PGPSignature, String>(); 25 private final Map<String, List<PGPSignature>> textsigs = new HashMap<>(); 26 private byte status; 27 private double reputation; 28 28 29 public TrustSignatures() {30 this.status = SIG_UNKNOWN;31 }29 public TrustSignatures() { 30 this.status = SIG_UNKNOWN; 31 } 32 32 33 public TrustSignatures(PGPSignature signature, String sigtext, byte status) {34 this.status = status;35 addSignature(signature, sigtext);36 }33 public TrustSignatures(PGPSignature signature, String sigtext, byte status) { 34 this.status = status; 35 addSignature(signature, sigtext); 36 } 37 37 38 public int countSigs() {39 //return signatures.size();40 //return signatureTextMap.size();41 int count = 0;42 for (List<PGPSignature> siglist : textsigs.values()) {43 count += siglist.size();44 }45 return count;46 }38 public int countSigs() { 39 // return signatures.size(); 40 //return signatureTextMap.size(); 41 int count = 0; 42 for (List<PGPSignature> siglist : textsigs.values()) { 43 count += siglist.size(); 44 } 45 return count; 46 } 47 47 48 public void setReputation(double r) {49 reputation = r;50 }48 public void setReputation(double r) { 49 reputation = r; 50 } 51 51 52 public double getReputation() {53 return reputation;54 }52 public double getReputation() { 53 return reputation; 54 } 55 55 56 public void setStatus(byte status) {57 this.status = status;58 }56 public void setStatus(byte status) { 57 this.status = status; 58 } 59 59 60 public byte getStatus() {61 return status;62 }60 public byte getStatus() { 61 return status; 62 } 63 63 64 /*public void setSignatures(Vector<PGPSignature> signatures) {65 this.signatures.addAll(signatures);66 }67 */68 public Vector<PGPSignature> getSignatures() {69 //return signatures;70 Vector<PGPSignature> sigs = new Vector<PGPSignature>();71 for (List<PGPSignature> siglist : textsigs.values()) {72 sigs.addAll(siglist);73 }74 return sigs;75 }64 /* public void setSignatures(Vector<PGPSignature> signatures) { 65 this.signatures.addAll(signatures); 66 } 67 */ 68 public Vector<PGPSignature> getSignatures() { 69 // return signatures; 70 Vector<PGPSignature> sigs = new Vector<>(); 71 for (List<PGPSignature> siglist : textsigs.values()) { 72 sigs.addAll(siglist); 73 } 74 return sigs; 75 } 76 76 77 public Map<String, List<PGPSignature>> getSignaturesWithText() {78 //return signatures;79 return textsigs;80 }77 public Map<String, List<PGPSignature>> getSignaturesWithText() { 78 // return signatures; 79 return textsigs; 80 } 81 81 82 public List<PGPSignature> getSignaturesByPlaintext(String plain) {83 return textsigs.get(plain);84 }82 public List<PGPSignature> getSignaturesByPlaintext(String plain) { 83 return textsigs.get(plain); 84 } 85 85 86 public void addSignature(PGPSignature signature, String sigtext) {87 //signatures.add(signature);88 //signatureTextMap.put(signature, sigtext);89 if (textsigs.containsKey(sigtext)) {90 textsigs.get(sigtext).add(signature);91 } else {92 List<PGPSignature> l = new ArrayList<PGPSignature>();93 l.add(signature);94 textsigs.put(sigtext, l);95 }96 }86 public void addSignature(PGPSignature signature, String sigtext) { 87 // signatures.add(signature); 88 //signatureTextMap.put(signature, sigtext); 89 if (textsigs.containsKey(sigtext)) { 90 textsigs.get(sigtext).add(signature); 91 } else { 92 List<PGPSignature> l = new ArrayList<>(); 93 l.add(signature); 94 textsigs.put(sigtext, l); 95 } 96 } 97 97 98 /*public void addSignatures(List<PGPSignature> signatures, String sigtext) {99 textsigs.get(sigtext).addAll(signatures);100 }101 */98 /* public void addSignatures(List<PGPSignature> signatures, String sigtext) { 99 textsigs.get(sigtext).addAll(signatures); 100 } 101 */ 102 102 103 /*104 public PGPSignature getLatestSignature() {105 return signatures.lastElement();106 }107 */108 public String getOnePlainText() {109 Set<String> texts = getAllPlainTexts();110 if (texts.isEmpty()) return "";111 else return texts.iterator().next();112 }103 /* 104 public PGPSignature getLatestSignature() { 105 return signatures.lastElement(); 106 } 107 */ 108 public String getOnePlainText() { 109 Set<String> texts = getAllPlainTexts(); 110 if (texts.isEmpty()) return ""; 111 else return texts.iterator().next(); 112 } 113 113 114 public Set<String> getAllPlainTexts() {115 return textsigs.keySet();116 }114 public Set<String> getAllPlainTexts() { 115 return textsigs.keySet(); 116 } 117 117 118 public String getSigtext(PGPSignature signature) {119 for (String sigtext : textsigs.keySet()) {120 if (textsigs.get(sigtext).contains(signature)) return sigtext;121 }122 return "";123 }118 public String getSigtext(PGPSignature signature) { 119 for (String sigtext : textsigs.keySet()) { 120 if (textsigs.get(sigtext).contains(signature)) return sigtext; 121 } 122 return ""; 123 } 124 124 125 public String getArmoredFulltextSignatureAll(String plain) {126 if (textsigs.containsKey(plain)){127 List<PGPSignature> l = textsigs.get(plain);128 try {129 ByteArrayOutputStream baos = new ByteArrayOutputStream();130 ArmoredOutputStream aOut = new ArmoredOutputStream(baos);131 aOut.beginClearText(l.get(0).getHashAlgorithm());132 aOut.write(plain.getBytes(Charset.forName("UTF-8")));133 aOut.write('\n');134 aOut.endClearText();125 public String getArmoredFulltextSignatureAll(String plain) { 126 if (textsigs.containsKey(plain)){ 127 List<PGPSignature> l = textsigs.get(plain); 128 try { 129 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 130 ArmoredOutputStream aOut = new ArmoredOutputStream(baos); 131 aOut.beginClearText(l.get(0).getHashAlgorithm()); 132 aOut.write(plain.getBytes(Charset.forName("UTF-8"))); 133 aOut.write('\n'); 134 aOut.endClearText(); 135 135 136 BCPGOutputStream bOut = new BCPGOutputStream(aOut);137 for (PGPSignature sig : l) {138 sig.encode(bOut);139 }136 BCPGOutputStream bOut = new BCPGOutputStream(aOut); 137 for (PGPSignature sig : l) { 138 sig.encode(bOut); 139 } 140 140 141 bOut.close();142 aOut.close();141 bOut.close(); 142 aOut.close(); 143 143 144 return baos.toString("UTF-8");144 return baos.toString("UTF-8"); 145 145 146 } catch (Exception e) {147 e.printStackTrace();148 return "Error - read console Output";149 }150 }151 return "No sigs available";152 }146 } catch (Exception e) { 147 e.printStackTrace(); 148 return "Error - read console Output"; 149 } 150 } 151 return "No sigs available"; 152 } 153 153 154 public String getArmoredFulltextSignature(PGPSignature sig) {155 try {156 ByteArrayOutputStream baos = new ByteArrayOutputStream();157 ArmoredOutputStream aOut = new ArmoredOutputStream(baos);158 aOut.beginClearText(sig.getHashAlgorithm());159 aOut.write(getSigtext(sig).getBytes(Charset.forName("UTF-8")));160 aOut.write('\n');161 aOut.endClearText();154 public String getArmoredFulltextSignature(PGPSignature sig) { 155 try { 156 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 157 ArmoredOutputStream aOut = new ArmoredOutputStream(baos); 158 aOut.beginClearText(sig.getHashAlgorithm()); 159 aOut.write(getSigtext(sig).getBytes(Charset.forName("UTF-8"))); 160 aOut.write('\n'); 161 aOut.endClearText(); 162 162 163 BCPGOutputStream bOut = new BCPGOutputStream(aOut);164 sig.encode(bOut);165 bOut.close();166 aOut.close();163 BCPGOutputStream bOut = new BCPGOutputStream(aOut); 164 sig.encode(bOut); 165 bOut.close(); 166 aOut.close(); 167 167 168 168 169 return baos.toString("UTF-8");170 } catch (Exception e) {171 e.printStackTrace();172 return "Error - read console Output";173 }174 }169 return baos.toString("UTF-8"); 170 } catch (Exception e) { 171 e.printStackTrace(); 172 return "Error - read console Output"; 173 } 174 } 175 175 176 176 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/data/TrustWay.java
r26053 r30724 14 14 public class TrustWay extends TrustOsmPrimitive { 15 15 16 /*17 public static List<WaySegment> generateSegmentListFromWay(Way w) {18 List<WaySegment> segList = new ArrayList<WaySegment>();19 for (int i = 0; i < w.getNodesCount()-1; i++) {20 segList.add(new WaySegment(w,i));21 }22 return segList;23 }24 */16 /* 17 public static List<WaySegment> generateSegmentListFromWay(Way w) { 18 List<WaySegment> segList = new ArrayList<WaySegment>(); 19 for (int i = 0; i < w.getNodesCount()-1; i++) { 20 segList.add(new WaySegment(w,i)); 21 } 22 return segList; 23 } 24 */ 25 25 26 public static List<Node> generateSegmentFromSigtext(String sigtext) {27 String[] lines = sigtext.split("\n");28 List<Node> nodes = new ArrayList<Node>();29 for (int i=1; i<lines.length; i++){30 nodes.add(TrustNode.generateNodeFromSigtext(lines[i]));31 }32 return nodes;33 }26 public static List<Node> generateSegmentFromSigtext(String sigtext) { 27 String[] lines = sigtext.split("\n"); 28 List<Node> nodes = new ArrayList<>(); 29 for (int i=1; i<lines.length; i++){ 30 nodes.add(TrustNode.generateNodeFromSigtext(lines[i])); 31 } 32 return nodes; 33 } 34 34 35 public static String generateSegmentSigtext(TrustWay trust, List<Node> nodes) {36 String sigtext = "WayID=" + trust.getOsmPrimitive().getUniqueId();37 for (Node n : nodes) {38 sigtext += "\n" + TrustNode.generateNodeSigtext(n);39 }40 return sigtext;41 }35 public static String generateSegmentSigtext(TrustWay trust, List<Node> nodes) { 36 String sigtext = "WayID=" + trust.getOsmPrimitive().getUniqueId(); 37 for (Node n : nodes) { 38 sigtext += "\n" + TrustNode.generateNodeSigtext(n); 39 } 40 return sigtext; 41 } 42 42 43 43 44 private final Map<List<Node>, TrustSignatures> segmentSig = new HashMap<List<Node>, TrustSignatures>();44 private final Map<List<Node>, TrustSignatures> segmentSig = new HashMap<>(); 45 45 46 public TrustWay(OsmPrimitive osmItem) {47 super(osmItem);48 }46 public TrustWay(OsmPrimitive osmItem) { 47 super(osmItem); 48 } 49 49 50 @Override51 public void setOsmPrimitive(OsmPrimitive osmItem) {52 if(osmItem instanceof Way) {53 osm = osmItem;54 } else {55 System.err.println("Error while creating TrustWay: OsmPrimitive "+osmItem.getUniqueId()+" is not a Way!");56 }57 }50 @Override 51 public void setOsmPrimitive(OsmPrimitive osmItem) { 52 if(osmItem instanceof Way) { 53 osm = osmItem; 54 } else { 55 System.err.println("Error while creating TrustWay: OsmPrimitive "+osmItem.getUniqueId()+" is not a Way!"); 56 } 57 } 58 58 59 59 60 public void storeSegmentSig(List<Node> nodes, PGPSignature sig) {61 if (segmentSig.containsKey(nodes)) {62 segmentSig.get(nodes).addSignature(sig, TrustWay.generateSegmentSigtext(this,nodes));63 } else {64 segmentSig.put(nodes, new TrustSignatures(sig, TrustWay.generateSegmentSigtext(this,nodes), TrustSignatures.SIG_VALID));65 }66 }60 public void storeSegmentSig(List<Node> nodes, PGPSignature sig) { 61 if (segmentSig.containsKey(nodes)) { 62 segmentSig.get(nodes).addSignature(sig, TrustWay.generateSegmentSigtext(this,nodes)); 63 } else { 64 segmentSig.put(nodes, new TrustSignatures(sig, TrustWay.generateSegmentSigtext(this,nodes), TrustSignatures.SIG_VALID)); 65 } 66 } 67 67 68 public void setSegmentRatings(List<Node> nodes, TrustSignatures tsigs) {69 segmentSig.put(nodes, tsigs);70 }68 public void setSegmentRatings(List<Node> nodes, TrustSignatures tsigs) { 69 segmentSig.put(nodes, tsigs); 70 } 71 71 72 public Map<List<Node>, TrustSignatures> getSegmentSigs() {73 return segmentSig;74 }72 public Map<List<Node>, TrustSignatures> getSegmentSigs() { 73 return segmentSig; 74 } 75 75 76 public TrustSignatures getSigsOnSegment(WaySegment seg) {77 List<Node> nodes = new ArrayList<Node>();78 nodes.add(seg.getFirstNode());79 nodes.add(seg.getSecondNode());80 return getSigsOnSegment(nodes);81 }76 public TrustSignatures getSigsOnSegment(WaySegment seg) { 77 List<Node> nodes = new ArrayList<>(); 78 nodes.add(seg.getFirstNode()); 79 nodes.add(seg.getSecondNode()); 80 return getSigsOnSegment(nodes); 81 } 82 82 83 public TrustSignatures getSigsOnSegment(List<Node> nodes) {84 return segmentSig.get(nodes);85 }83 public TrustSignatures getSigsOnSegment(List<Node> nodes) { 84 return segmentSig.get(nodes); 85 } 86 86 87 87 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/DownloadSignedOsmDataTask.java
r26518 r30724 25 25 public class DownloadSignedOsmDataTask extends PleaseWaitRunnable { 26 26 27 private boolean canceled;28 private Exception lastException;29 private final Collection<OsmPrimitive> missing;30 private final OsmDataLayer curLayer;31 private MultiFetchServerObjectReader objectReader;27 private boolean canceled; 28 private Exception lastException; 29 private final Collection<OsmPrimitive> missing; 30 private final OsmDataLayer curLayer; 31 private MultiFetchServerObjectReader objectReader; 32 32 33 /**34 * Download the given OSMPrimitives to the given layer35 *36 */37 public DownloadSignedOsmDataTask(Collection<OsmPrimitive> missing, OsmDataLayer curLayer) {38 super(tr("Download signed data"));39 this.missing = missing;40 this.curLayer = curLayer;41 }33 /** 34 * Download the given OSMPrimitives to the given layer 35 * 36 */ 37 public DownloadSignedOsmDataTask(Collection<OsmPrimitive> missing, OsmDataLayer curLayer) { 38 super(tr("Download signed data")); 39 this.missing = missing; 40 this.curLayer = curLayer; 41 } 42 42 43 43 44 @Override45 protected void cancel() {46 canceled = true;47 synchronized(this) {48 if (objectReader != null) {49 objectReader.cancel();50 }51 }52 }44 @Override 45 protected void cancel() { 46 canceled = true; 47 synchronized(this) { 48 if (objectReader != null) { 49 objectReader.cancel(); 50 } 51 } 52 } 53 53 54 @Override55 protected void finish() {56 Main.map.repaint();57 if (canceled)58 return;59 if (lastException != null) {60 ExceptionDialogUtil.explainException(lastException);61 }62 }54 @Override 55 protected void finish() { 56 Main.map.repaint(); 57 if (canceled) 58 return; 59 if (lastException != null) { 60 ExceptionDialogUtil.explainException(lastException); 61 } 62 } 63 63 64 protected String buildDownloadFeedbackMessage() {65 return trn("Downloading {0} incomplete child of relation ''{1}''",66 "Downloading {0} incomplete children of relation ''{1}''",67 missing.size(),68 missing.size(),69 "Wurst"70 );71 }64 protected String buildDownloadFeedbackMessage() { 65 return trn("Downloading {0} incomplete child of relation ''{1}''", 66 "Downloading {0} incomplete children of relation ''{1}''", 67 missing.size(), 68 missing.size(), 69 "Wurst" 70 ); 71 } 72 72 73 @Override74 protected void realRun() throws SAXException, IOException, OsmTransferException {75 try {76 synchronized (this) {77 if (canceled) return;78 objectReader = new MultiFetchServerObjectReader();79 }80 objectReader.append(missing);81 progressMonitor.indeterminateSubTask(82 buildDownloadFeedbackMessage()83 );84 final DataSet dataSet = objectReader.parseOsm(progressMonitor85 .createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));86 if (dataSet == null)87 return;88 synchronized (this) {89 if (canceled) return;90 objectReader = null;91 }73 @Override 74 protected void realRun() throws SAXException, IOException, OsmTransferException { 75 try { 76 synchronized (this) { 77 if (canceled) return; 78 objectReader = new MultiFetchServerObjectReader(); 79 } 80 objectReader.append(missing); 81 progressMonitor.indeterminateSubTask( 82 buildDownloadFeedbackMessage() 83 ); 84 final DataSet dataSet = objectReader.parseOsm(progressMonitor 85 .createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)); 86 if (dataSet == null) 87 return; 88 synchronized (this) { 89 if (canceled) return; 90 objectReader = null; 91 } 92 92 93 SwingUtilities.invokeLater(94 new Runnable() {95 public void run() {96 curLayer.mergeFrom(dataSet);97 curLayer.onPostDownloadFromServer();98 AutoScaleAction.zoomTo(dataSet.allPrimitives());99 updateReferences(dataSet);100 }101 }102 );93 SwingUtilities.invokeLater( 94 new Runnable() { 95 public void run() { 96 curLayer.mergeFrom(dataSet); 97 curLayer.onPostDownloadFromServer(); 98 AutoScaleAction.zoomTo(dataSet.allPrimitives()); 99 updateReferences(dataSet); 100 } 101 } 102 ); 103 103 104 } catch (Exception e) {105 if (canceled) {106 System.out.println(tr("Warning: Ignoring exception because task was canceled. Exception: {0}", e.toString()));107 return;108 }109 lastException = e;110 }111 }104 } catch (Exception e) { 105 if (canceled) { 106 System.out.println(tr("Warning: Ignoring exception because task was canceled. Exception: {0}", e.toString())); 107 return; 108 } 109 lastException = e; 110 } 111 } 112 112 113 public boolean updateReferences(DataSet ds) {114 for (TrustOsmPrimitive t : TrustOSMplugin.signedItems.values()) {115 OsmPrimitive osm = ds.getPrimitiveById(t.getOsmPrimitive().getPrimitiveId());116 if (osm != null) {117 t.setOsmPrimitive(osm);118 return true;119 } else {120 System.out.println("No item found");121 }122 }123 return false;124 }113 public boolean updateReferences(DataSet ds) { 114 for (TrustOsmPrimitive t : TrustOSMplugin.signedItems.values()) { 115 OsmPrimitive osm = ds.getPrimitiveById(t.getOsmPrimitive().getPrimitiveId()); 116 if (osm != null) { 117 t.setOsmPrimitive(osm); 118 return true; 119 } else { 120 System.out.println("No item found"); 121 } 122 } 123 return false; 124 } 125 125 126 126 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/KeyGenerationTask.java
r26518 r30724 12 12 public class KeyGenerationTask extends PleaseWaitRunnable { 13 13 14 private boolean canceled;15 private Exception lastException;14 private boolean canceled; 15 private Exception lastException; 16 16 17 public KeyGenerationTask() {18 super(tr("Generating new Keypair.\nCollecting randomness..."));19 }17 public KeyGenerationTask() { 18 super(tr("Generating new Keypair.\nCollecting randomness...")); 19 } 20 20 21 @Override22 protected void cancel() {23 canceled = true;24 synchronized(this) {25 /*if (objectReader != null) {26 objectReader.cancel();27 }*/28 }29 }21 @Override 22 protected void cancel() { 23 canceled = true; 24 synchronized(this) { 25 /* if (objectReader != null) { 26 objectReader.cancel(); 27 }*/ 28 } 29 } 30 30 31 @Override32 protected void finish() {33 if (canceled)34 return;35 if (lastException != null) {36 ExceptionDialogUtil.explainException(lastException);37 }31 @Override 32 protected void finish() { 33 if (canceled) 34 return; 35 if (lastException != null) { 36 ExceptionDialogUtil.explainException(lastException); 37 } 38 38 39 }39 } 40 40 41 @Override42 protected void realRun() throws SAXException, IOException,43 OsmTransferException {44 try {45 /*synchronized (this) {46 if (canceled) return;47 objectReader = new MultiFetchServerObjectReader();48 }49 objectReader.append(missing);50 progressMonitor.indeterminateSubTask(51 buildDownloadFeedbackMessage()52 );53 final DataSet dataSet = objectReader.parseOsm(progressMonitor54 .createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false));55 if (dataSet == null)56 return;57 synchronized (this) {58 if (canceled) return;59 objectReader = null;60 }41 @Override 42 protected void realRun() throws SAXException, IOException, 43 OsmTransferException { 44 try { 45 /* synchronized (this) { 46 if (canceled) return; 47 objectReader = new MultiFetchServerObjectReader(); 48 } 49 objectReader.append(missing); 50 progressMonitor.indeterminateSubTask( 51 buildDownloadFeedbackMessage() 52 ); 53 final DataSet dataSet = objectReader.parseOsm(progressMonitor 54 .createSubTaskMonitor(ProgressMonitor.ALL_TICKS, false)); 55 if (dataSet == null) 56 return; 57 synchronized (this) { 58 if (canceled) return; 59 objectReader = null; 60 } 61 61 62 SwingUtilities.invokeLater(63 new Runnable() {64 public void run() {65 curLayer.mergeFrom(dataSet);66 curLayer.onPostDownloadFromServer();67 AutoScaleAction.zoomTo(dataSet.allPrimitives());68 }69 }70 );71 */72 } catch (Exception e) {73 if (canceled) {74 System.out.println(tr("Warning: Ignoring exception because task was canceled. Exception: {0}", e75 .toString()));76 return;77 }78 lastException = e;79 }62 SwingUtilities.invokeLater( 63 new Runnable() { 64 public void run() { 65 curLayer.mergeFrom(dataSet); 66 curLayer.onPostDownloadFromServer(); 67 AutoScaleAction.zoomTo(dataSet.allPrimitives()); 68 } 69 } 70 ); 71 */ 72 } catch (Exception e) { 73 if (canceled) { 74 System.out.println(tr("Warning: Ignoring exception because task was canceled. Exception: {0}", e 75 .toString())); 76 return; 77 } 78 lastException = e; 79 } 80 80 81 }81 } 82 82 83 83 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/KeyTreeTableModel.java
r25269 r30724 20 20 public class KeyTreeTableModel extends AbstractTreeTableModel { 21 21 22 public static String convPGPSignatureToString(PGPSignature s) {23 if (s==null) return null;24 PGPSignatureSubpacketVector sv = s.getHashedSubPackets();25 if (sv != null && sv.hasSubpacket(SignatureSubpacketTags.SIGNER_USER_ID))26 return sv.getSignerUserID();22 public static String convPGPSignatureToString(PGPSignature s) { 23 if (s==null) return null; 24 PGPSignatureSubpacketVector sv = s.getHashedSubPackets(); 25 if (sv != null && sv.hasSubpacket(SignatureSubpacketTags.SIGNER_USER_ID)) 26 return sv.getSignerUserID(); 27 27 28 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID());29 if (pub != null){30 Iterator i = pub.getUserIDs();31 if (i.hasNext())32 return (String)i.next();28 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID()); 29 if (pub != null){ 30 Iterator<?> i = pub.getUserIDs(); 31 if (i.hasNext()) 32 return (String)i.next(); 33 33 34 }35 return tr("unknown");36 }34 } 35 return tr("unknown"); 36 } 37 37 38 private final SignatureTreeNode root;39 private final String[] allTitle = {tr("UID"),tr("KeyID"),tr("OSM-Info"),tr("Signed")};40 private final List<String> columns = new ArrayList<String>(Arrays.asList(allTitle));38 private final SignatureTreeNode root; 39 private final String[] allTitle = {tr("UID"),tr("KeyID"),tr("OSM-Info"),tr("Signed")}; 40 private final List<String> columns = new ArrayList<>(Arrays.asList(allTitle)); 41 41 42 public KeyTreeTableModel(Collection<PGPSignature> sigs) {43 root = new SignatureTreeNode();44 for (PGPSignature s : sigs){45 SignatureTreeNode sn = new SignatureTreeNode(s);46 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID());47 Iterator iter = pub.getSignatures();48 while (iter.hasNext()){49 PGPSignature ks = (PGPSignature)iter.next();50 sn.getChildren().add(new SignatureTreeNode(ks));51 }52 root.getChildren().add(sn);53 }54 }42 public KeyTreeTableModel(Collection<PGPSignature> sigs) { 43 root = new SignatureTreeNode(); 44 for (PGPSignature s : sigs){ 45 SignatureTreeNode sn = new SignatureTreeNode(s); 46 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID()); 47 Iterator<?> iter = pub.getSignatures(); 48 while (iter.hasNext()){ 49 PGPSignature ks = (PGPSignature)iter.next(); 50 sn.getChildren().add(new SignatureTreeNode(ks)); 51 } 52 root.getChildren().add(sn); 53 } 54 } 55 55 56 @Override57 public int getColumnCount() {58 return columns.size();59 }56 @Override 57 public int getColumnCount() { 58 return columns.size(); 59 } 60 60 61 @Override62 public String getColumnName( int column ) {63 String title = columns.get(column);64 if (title != null)65 return title;66 return tr("Unknown");67 }61 @Override 62 public String getColumnName( int column ) { 63 String title = columns.get(column); 64 if (title != null) 65 return title; 66 return tr("Unknown"); 67 } 68 68 69 69 70 @Override71 public Object getValueAt(Object node, int column) {72 SignatureTreeNode signode = ( SignatureTreeNode )node;73 String title = columns.get(column);74 if (title != null){75 if (title.equals(allTitle[0]))76 return signode.getUID();77 if (title.equals(allTitle[1]))78 return signode.getKeyID();79 if (title.equals(allTitle[2]))80 return signode.getOsmCertificate();81 if (title.equals(allTitle[3]))82 return signode.getSignatureDate();83 }84 return tr("Unknown");70 @Override 71 public Object getValueAt(Object node, int column) { 72 SignatureTreeNode signode = ( SignatureTreeNode )node; 73 String title = columns.get(column); 74 if (title != null){ 75 if (title.equals(allTitle[0])) 76 return signode.getUID(); 77 if (title.equals(allTitle[1])) 78 return signode.getKeyID(); 79 if (title.equals(allTitle[2])) 80 return signode.getOsmCertificate(); 81 if (title.equals(allTitle[3])) 82 return signode.getSignatureDate(); 83 } 84 return tr("Unknown"); 85 85 86 }86 } 87 87 88 @Override89 public Object getChild(Object node, int index) {90 SignatureTreeNode signode = ( SignatureTreeNode )node;91 return signode.getChildren().get( index );92 }88 @Override 89 public Object getChild(Object node, int index) { 90 SignatureTreeNode signode = ( SignatureTreeNode )node; 91 return signode.getChildren().get( index ); 92 } 93 93 94 @Override95 public int getChildCount(Object node) {96 SignatureTreeNode signode = ( SignatureTreeNode )node;97 return signode.getChildren().size();98 }94 @Override 95 public int getChildCount(Object node) { 96 SignatureTreeNode signode = ( SignatureTreeNode )node; 97 return signode.getChildren().size(); 98 } 99 99 100 @Override101 public int getIndexOfChild( Object parent, Object child ) {102 SignatureTreeNode signode = ( SignatureTreeNode )parent;103 for( int i=0; i>signode.getChildren().size(); i++ ) {104 if( signode.getChildren().get( i ) == child )105 return i;106 }107 return 0;108 }100 @Override 101 public int getIndexOfChild( Object parent, Object child ) { 102 SignatureTreeNode signode = ( SignatureTreeNode )parent; 103 for( int i=0; i>signode.getChildren().size(); i++ ) { 104 if( signode.getChildren().get( i ) == child ) 105 return i; 106 } 107 return 0; 108 } 109 109 110 @Override111 public Object getRoot() {112 return root;113 }110 @Override 111 public Object getRoot() { 112 return root; 113 } 114 114 115 115 116 public class SignatureTreeNode {117 private PGPSignature s;118 private final List<SignatureTreeNode> children = new ArrayList<SignatureTreeNode>();119 private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss");120 public SignatureTreeNode() {121 }116 public class SignatureTreeNode { 117 private PGPSignature s; 118 private final List<SignatureTreeNode> children = new ArrayList<>(); 119 private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss"); 120 public SignatureTreeNode() { 121 } 122 122 123 public SignatureTreeNode(PGPSignature s) {124 this.s = s;125 }123 public SignatureTreeNode(PGPSignature s) { 124 this.s = s; 125 } 126 126 127 public PGPSignature getSignature(){128 return s;129 }130 public String getUID() {131 return convPGPSignatureToString(s);132 }133 public String getKeyID() {134 return "0x"+Long.toHexString(s.getKeyID()).substring(8).toUpperCase();135 }136 public String getOsmCertificate() {137 String cert = "";138 for (NotationData nd : s.getHashedSubPackets().getNotationDataOccurences()){139 if (nd.getNotationName().equals("trustosm@openstreetmap.org")) {140 cert += nd.getNotationValue();141 }142 }143 return cert;144 }145 public String getSignatureDate() {146 return formatter.format(s.getCreationTime());147 }148 public List<SignatureTreeNode> getChildren() {149 return children;150 }127 public PGPSignature getSignature(){ 128 return s; 129 } 130 public String getUID() { 131 return convPGPSignatureToString(s); 132 } 133 public String getKeyID() { 134 return "0x"+Long.toHexString(s.getKeyID()).substring(8).toUpperCase(); 135 } 136 public String getOsmCertificate() { 137 String cert = ""; 138 for (NotationData nd : s.getHashedSubPackets().getNotationDataOccurences()){ 139 if (nd.getNotationName().equals("trustosm@openstreetmap.org")) { 140 cert += nd.getNotationValue(); 141 } 142 } 143 return cert; 144 } 145 public String getSignatureDate() { 146 return formatter.format(s.getCreationTime()); 147 } 148 public List<SignatureTreeNode> getChildren() { 149 return children; 150 } 151 151 152 }152 } 153 153 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/JCollapsiblePanel.java
r24389 r30724 14 14 public class JCollapsiblePanel extends JPanel { 15 15 16 private boolean expanded;17 JPanel contentPanel_;18 HeaderPanel headerPanel_;16 private boolean expanded; 17 JPanel contentPanel_; 18 HeaderPanel headerPanel_; 19 19 20 private class HeaderPanel extends JPanel {21 JLabel title;20 private class HeaderPanel extends JPanel { 21 JLabel title; 22 22 23 public HeaderPanel(String text) {23 public HeaderPanel(String text) { 24 24 25 setLayout(new GridBagLayout());26 title = new JLabel(text,ImageProvider.get("misc", "minimized"),SwingConstants.LEADING);27 add(title,GBC.eol());25 setLayout(new GridBagLayout()); 26 title = new JLabel(text,ImageProvider.get("misc", "minimized"),SwingConstants.LEADING); 27 add(title,GBC.eol()); 28 28 29 29 30 addMouseListener(31 new MouseAdapter() {32 @Override33 public void mouseClicked(MouseEvent e) {34 expanded = !expanded;30 addMouseListener( 31 new MouseAdapter() { 32 @Override 33 public void mouseClicked(MouseEvent e) { 34 expanded = !expanded; 35 35 36 if (contentPanel_.isShowing()) {37 contentPanel_.setVisible(false);38 title.setIcon(ImageProvider.get("misc", "minimized"));39 }40 else {41 contentPanel_.setVisible(true);42 title.setIcon(ImageProvider.get("misc", "normal"));43 }44 validate();36 if (contentPanel_.isShowing()) { 37 contentPanel_.setVisible(false); 38 title.setIcon(ImageProvider.get("misc", "minimized")); 39 } 40 else { 41 contentPanel_.setVisible(true); 42 title.setIcon(ImageProvider.get("misc", "normal")); 43 } 44 validate(); 45 45 46 headerPanel_.repaint();47 }48 }49 );46 headerPanel_.repaint(); 47 } 48 } 49 ); 50 50 51 }51 } 52 52 53 }53 } 54 54 55 public JCollapsiblePanel(String text, JPanel panel) {56 super(new GridBagLayout());57 expanded = false;58 headerPanel_ = new HeaderPanel(text);59 contentPanel_ = panel;60 add(headerPanel_, GBC.eol());61 add(contentPanel_, GBC.eol());62 contentPanel_.setVisible(false);63 }55 public JCollapsiblePanel(String text, JPanel panel) { 56 super(new GridBagLayout()); 57 expanded = false; 58 headerPanel_ = new HeaderPanel(text); 59 contentPanel_ = panel; 60 add(headerPanel_, GBC.eol()); 61 add(contentPanel_, GBC.eol()); 62 contentPanel_.setVisible(false); 63 } 64 64 65 65 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/KeySignaturesDialog.java
r24389 r30724 22 22 public class KeySignaturesDialog extends JPanel { 23 23 24 protected boolean isCollapsed;24 protected boolean isCollapsed; 25 25 26 protected TitleBar titleBar;26 protected TitleBar titleBar; 27 27 28 /** the label in the title bar which shows whether the toggle dialog is expanded or collapsed */29 private JLabel lblMinimized;28 /** the label in the title bar which shows whether the toggle dialog is expanded or collapsed */ 29 private JLabel lblMinimized; 30 30 31 31 32 public KeySignaturesDialog(PGPPublicKey key) {33 super(new BorderLayout());32 public KeySignaturesDialog(PGPPublicKey key) { 33 super(new BorderLayout()); 34 34 35 String userid = "Unknown";36 Iterator iter = key.getUserIDs();37 if (iter.hasNext()) {38 userid = (String)iter.next();39 }35 String userid = "Unknown"; 36 Iterator<?> iter = key.getUserIDs(); 37 if (iter.hasNext()) { 38 userid = (String)iter.next(); 39 } 40 40 41 isCollapsed = false;41 isCollapsed = false; 42 42 43 titleBar = new TitleBar(userid);44 add(titleBar, BorderLayout.NORTH);45 add(createKeySigPanel(key));43 titleBar = new TitleBar(userid); 44 add(titleBar, BorderLayout.NORTH); 45 add(createKeySigPanel(key)); 46 46 47 }47 } 48 48 49 public static JPanel createKeySigPanel(PGPPublicKey key) {50 JPanel p = new JPanel();51 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));52 Iterator iter = key.getSignatures();53 while (iter.hasNext()) {54 PGPSignature sig = (PGPSignature)iter.next();55 String uid = "0x"+Long.toHexString(sig.getKeyID()).substring(8).toUpperCase();56 p.add(new JLabel(uid));57 }58 return p;59 }49 public static JPanel createKeySigPanel(PGPPublicKey key) { 50 JPanel p = new JPanel(); 51 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); 52 Iterator<?> iter = key.getSignatures(); 53 while (iter.hasNext()) { 54 PGPSignature sig = (PGPSignature)iter.next(); 55 String uid = "0x"+Long.toHexString(sig.getKeyID()).substring(8).toUpperCase(); 56 p.add(new JLabel(uid)); 57 } 58 return p; 59 } 60 60 61 /**62 * Collapses the toggle dialog to the title bar only63 *64 */65 public void collapse() {66 if (!isCollapsed) {67 //setContentVisible(false);68 isCollapsed = true;69 setPreferredSize(new Dimension(0,20));70 setMaximumSize(new Dimension(Integer.MAX_VALUE,20));71 setMinimumSize(new Dimension(Integer.MAX_VALUE,20));72 lblMinimized.setIcon(ImageProvider.get("misc", "minimized"));73 }74 else throw new IllegalStateException();75 }61 /** 62 * Collapses the toggle dialog to the title bar only 63 * 64 */ 65 public void collapse() { 66 if (!isCollapsed) { 67 //setContentVisible(false); 68 isCollapsed = true; 69 setPreferredSize(new Dimension(0,20)); 70 setMaximumSize(new Dimension(Integer.MAX_VALUE,20)); 71 setMinimumSize(new Dimension(Integer.MAX_VALUE,20)); 72 lblMinimized.setIcon(ImageProvider.get("misc", "minimized")); 73 } 74 else throw new IllegalStateException(); 75 } 76 76 77 /**78 * Expands the toggle dialog79 */80 protected void expand() {81 if (isCollapsed) {82 //setContentVisible(true);83 isCollapsed = false;84 setPreferredSize(new Dimension(0,200));85 setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE));86 lblMinimized.setIcon(ImageProvider.get("misc", "normal"));87 }88 else throw new IllegalStateException();89 }77 /** 78 * Expands the toggle dialog 79 */ 80 protected void expand() { 81 if (isCollapsed) { 82 // setContentVisible(true); 83 isCollapsed = false; 84 setPreferredSize(new Dimension(0,200)); 85 setMaximumSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); 86 lblMinimized.setIcon(ImageProvider.get("misc", "normal")); 87 } 88 else throw new IllegalStateException(); 89 } 90 90 91 /**92 * Sets the visibility of all components in this toggle dialog, except the title bar93 *94 * @param visible true, if the components should be visible; false otherwise95 */96 protected void setContentVisible(boolean visible) {97 Component comps[] = getComponents();98 for(int i=0; i<comps.length; i++) {99 if(comps[i] != titleBar) {100 comps[i].setVisible(visible);101 }102 }103 }91 /** 92 * Sets the visibility of all components in this toggle dialog, except the title bar 93 * 94 * @param visible true, if the components should be visible; false otherwise 95 */ 96 protected void setContentVisible(boolean visible) { 97 Component comps[] = getComponents(); 98 for(int i=0; i<comps.length; i++) { 99 if(comps[i] != titleBar) { 100 comps[i].setVisible(visible); 101 } 102 } 103 } 104 104 105 /**106 * The title bar displayed in docked mode107 *108 */109 protected class TitleBar extends JPanel {110 final private JLabel lblTitle;105 /** 106 * The title bar displayed in docked mode 107 * 108 */ 109 protected class TitleBar extends JPanel { 110 final private JLabel lblTitle; 111 111 112 public TitleBar(String toggleDialogName) {113 setLayout(new GridBagLayout());114 lblMinimized = new JLabel(ImageProvider.get("misc", "minimized"));115 add(lblMinimized);112 public TitleBar(String toggleDialogName) { 113 setLayout(new GridBagLayout()); 114 lblMinimized = new JLabel(ImageProvider.get("misc", "minimized")); 115 add(lblMinimized); 116 116 117 lblTitle = new JLabel(toggleDialogName);118 add(lblTitle, GBC.std().fill(GBC.HORIZONTAL));117 lblTitle = new JLabel(toggleDialogName); 118 add(lblTitle, GBC.std().fill(GBC.HORIZONTAL)); 119 119 120 addMouseListener(121 new MouseAdapter() {122 @Override123 public void mouseClicked(MouseEvent e) {124 // toggleExpandedState125 if (isCollapsed) {126 expand();127 } else {128 collapse();129 }130 }131 }132 );120 addMouseListener( 121 new MouseAdapter() { 122 @Override 123 public void mouseClicked(MouseEvent e) { 124 // toggleExpandedState 125 if (isCollapsed) { 126 expand(); 127 } else { 128 collapse(); 129 } 130 } 131 } 132 ); 133 133 134 setToolTipText(tr("Click to minimize/maximize the panel content"));135 setTitle(toggleDialogName);136 }134 setToolTipText(tr("Click to minimize/maximize the panel content")); 135 setTitle(toggleDialogName); 136 } 137 137 138 public void setTitle(String title) {139 lblTitle.setText(title);140 }138 public void setTitle(String title) { 139 lblTitle.setText(title); 140 } 141 141 142 public String getTitle() {143 return lblTitle.getText();144 }145 }142 public String getTitle() { 143 return lblTitle.getText(); 144 } 145 } 146 146 147 147 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/TrustDialog.java
r27852 r30724 70 70 public class TrustDialog extends ToggleDialog implements ActionListener, SelectionChangedListener, MapViewPaintable { 71 71 72 /**73 *74 */75 private static final long serialVersionUID = -3324984194315776740L;76 77 78 public final static Color BGCOLOR_NO_SIG = new Color(234, 234, 234);79 //public final static Color BGCOLOR_VALID_SIG = new Color(235,255,177);80 public final static Color BGCOLOR_VALID_SIG = new Color(74,245,106);81 public final static Color BGCOLOR_BROKEN_SIG = new Color(255, 197, 197);82 public final static Color BGCOLOR_REMOVED_ITEM = new Color(255, 100, 100);83 public final static Color BGCOLOR_UPDATED_ITEM = new Color(249,221,95);84 85 86 /** Use a TrustGPGPreparer to sign or validate signatures */87 //private final TrustGPGPreparer gpg;88 89 /** The check signatures button */90 private final SideButton checkButton;91 92 /** The sign button */93 private final SideButton signButton;94 95 /** The show sigs button */96 private final SideButton showButton;97 98 private final Map<String, Byte> rowStatus = new HashMap<String, Byte>();99 100 /** The selected osmData */101 private Collection<? extends OsmPrimitive> osmData;102 103 104 private final List<WaySegment> selectedSegments = new ArrayList<WaySegment>();105 private final List<OsmPrimitive> selectedPrimitives = new ArrayList<OsmPrimitive>();106 107 /** The JTree for showing the geometry */108 private final JTree geomTree;109 110 111 /**112 * The property data.113 */114 private final DefaultTableModel propertyData = new DefaultTableModel() {115 /**116 *117 */118 private static final long serialVersionUID = -1252801283184909691L;119 @Override public boolean isCellEditable(int row, int column) {120 return false;121 }122 @Override public Class<?> getColumnClass(int columnIndex) {123 return String.class;124 }125 };126 private final JTable propertyTable = new JTable(propertyData) {127 /**128 *129 */130 private static final long serialVersionUID = 1L;131 132 @Override133 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {134 Component c = super.prepareRenderer(renderer, row, column);135 Byte stat = rowStatus.get(getModel().getValueAt(row, 0));136 if (!isRowSelected(row))137 switch (stat.byteValue()) {138 case -2: c.setBackground( BGCOLOR_REMOVED_ITEM ); break;139 case -1: c.setBackground( BGCOLOR_BROKEN_SIG ); break;140 case 1: c.setBackground( BGCOLOR_VALID_SIG ); break;141 default: c.setBackground( BGCOLOR_NO_SIG ); break;142 }143 return c;144 }145 };146 147 /** The JTable for members of a relation */148 private final DefaultTableModel memberData = new DefaultTableModel() {149 150 /**151 *152 */153 private static final long serialVersionUID = 1L;154 @Override public boolean isCellEditable(int row, int column) {155 return false;156 }157 @Override public Class<?> getColumnClass(int columnIndex) {158 return String.class;159 }160 };161 private final JTable memberTable = new JTable(memberData) {162 /**163 *164 */165 private static final long serialVersionUID = 1L;166 167 @Override168 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {169 Component c = super.prepareRenderer(renderer, row, column);170 Byte stat = rowStatus.get(getModel().getValueAt(row, 0));171 if (!isRowSelected(row))172 switch (stat.byteValue()) {173 case -2: c.setBackground( BGCOLOR_REMOVED_ITEM ); break;174 case -1: c.setBackground( BGCOLOR_BROKEN_SIG ); break;175 case 1: c.setBackground( BGCOLOR_VALID_SIG ); break;176 default: c.setBackground( BGCOLOR_NO_SIG ); break;177 }178 return c;179 }180 };181 182 183 /**184 * Constructor185 */186 public TrustDialog() {187 super(tr("Object signatures"), "trustosm", tr("Open object signing window."),188 Shortcut.registerShortcut("subwindow:trustosm", tr("Toggle: {0}", tr("Object signatures")),189 KeyEvent.VK_T, Shortcut.ALT_CTRL), 150);190 191 Main.map.mapView.addTemporaryLayer(this);192 193 // setting up the properties table194 propertyData.setColumnIdentifiers(new String[]{tr("Key"),tr("Value")});195 196 // copy and paste from org.openstreetmap.josm.gui.dialogs.properties.PropertiesDialog197 198 propertyTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer(){199 /**200 *201 */202 private static final long serialVersionUID = 8003207668070727861L;203 204 @Override205 public Component getTableCellRendererComponent(JTable table, Object value,206 boolean isSelected, boolean hasFocus, int row, int column) {207 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);208 if (c instanceof JLabel) {209 String str = null;210 if (value instanceof String) {211 str = (String) value;212 } else if (value instanceof Map<?, ?>) {213 Map<?, ?> v = (Map<?, ?>) value;214 if (v.size() != 1) {215 str=tr("<different>");216 c.setFont(c.getFont().deriveFont(Font.ITALIC));217 } else {218 final Map.Entry<?, ?> entry = v.entrySet().iterator().next();219 str = (String) entry.getKey();220 }221 }222 ((JLabel)c).setText(str);223 }224 return c;225 }226 });227 228 geomTree = new JTree( createTree() );229 230 geomTree.setBackground( BGCOLOR_NO_SIG );231 geomTree.setRootVisible(false);232 geomTree.setCellRenderer(new DefaultTreeCellRenderer(){233 234 /**235 *236 */237 private static final long serialVersionUID = -3070210847060314196L;238 239 @Override240 public Component getTreeCellRendererComponent(JTree tree, Object value,241 boolean selected, boolean expanded, boolean leaf, int row,242 boolean hasFocus)243 {244 super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);245 246 DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;247 if (node.isRoot()) return this;248 setBackgroundNonSelectionColor( BGCOLOR_NO_SIG );249 Object o = node.getUserObject();250 if (o instanceof OsmPrimitive){251 OsmPrimitive osm = (OsmPrimitive) o;252 setIcon(ImageProvider.get(OsmPrimitiveType.from(osm)));253 setText(osm.getDisplayName(DefaultNameFormatter.getInstance()));254 255 256 if (osm instanceof Node) {257 Node osmNode = (Node) osm;258 TrustSignatures sigs;259 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);260 if (TrustOSMplugin.signedItems.containsKey(id) && (sigs = ((TrustNode)TrustOSMplugin.signedItems.get(id)).getNodeSigs()) != null) {261 byte stat = sigs.getStatus();262 switch (stat) {263 case -2: setBackgroundNonSelectionColor( BGCOLOR_REMOVED_ITEM ); break;264 case -1: setBackgroundNonSelectionColor( BGCOLOR_BROKEN_SIG ); break;265 case 1: setBackgroundNonSelectionColor( BGCOLOR_VALID_SIG ); break;266 default: setBackgroundNonSelectionColor( BGCOLOR_NO_SIG ); break;267 }268 }269 } else if (osm instanceof Way) {270 //setBackgroundNonSelectionColor( BGCOLOR_NO_SIG );271 }272 273 } else if (o instanceof WaySegment){274 WaySegment seg = (WaySegment) o;275 setIcon(ImageProvider.get("mapmode/addsegment"));276 setText(seg.getFirstNode().getDisplayName(DefaultNameFormatter.getInstance()) + " ----- " + seg.getSecondNode().getDisplayName(DefaultNameFormatter.getInstance()));277 TrustSignatures sigs;278 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(seg.way);279 if (TrustOSMplugin.signedItems.containsKey(id) && (sigs = ((TrustWay)TrustOSMplugin.signedItems.get(id)).getSigsOnSegment(seg)) != null) {280 byte stat = sigs.getStatus();281 switch (stat) {282 case -2: setBackgroundNonSelectionColor( BGCOLOR_REMOVED_ITEM ); break;283 case -1: setBackgroundNonSelectionColor( BGCOLOR_BROKEN_SIG ); break;284 case 1: setBackgroundNonSelectionColor( BGCOLOR_VALID_SIG ); break;285 default: setBackgroundNonSelectionColor( BGCOLOR_NO_SIG ); break;286 }287 }288 }289 return this;290 }291 292 293 });294 295 geomTree.addTreeSelectionListener(new TreeSelectionListener() {296 public void valueChanged(TreeSelectionEvent e) {297 // unhighlight everything298 for (OsmPrimitive p : selectedPrimitives) {299 p.setHighlighted(false);300 }301 selectedPrimitives.clear();302 selectedSegments.clear();303 if (geomTree.getSelectionPaths()!=null)304 for (TreePath tp : geomTree.getSelectionPaths()) {305 Object o = ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject();306 if (o instanceof WaySegment) {307 selectedSegments.add((WaySegment) o);308 } else if (o instanceof OsmPrimitive) {309 OsmPrimitive highlight = (OsmPrimitive) o;310 highlight.setHighlighted(true);311 selectedPrimitives.add(highlight);312 }313 }314 Main.map.mapView.repaint();315 }316 });317 318 propertyTable.addFocusListener(new FocusListener(){319 320 @Override321 public void focusGained(FocusEvent fe) {322 geomTree.clearSelection();323 324 }325 326 @Override327 public void focusLost(FocusEvent fe) {328 329 }330 331 });332 333 geomTree.addFocusListener(new FocusListener(){334 335 @Override336 public void focusGained(FocusEvent fe) {337 propertyTable.clearSelection();338 339 }340 341 @Override342 public void focusLost(FocusEvent fe) {343 344 }345 346 });347 348 JPanel dataPanel = new JPanel();349 dataPanel.setLayout(new BoxLayout(dataPanel, BoxLayout.PAGE_AXIS));350 propertyTable.setAlignmentX(LEFT_ALIGNMENT);351 dataPanel.add(propertyTable);352 geomTree.setAlignmentX(LEFT_ALIGNMENT);353 dataPanel.add(geomTree);354 355 checkButton = new SideButton(marktr("Check"), "checksignatures", "TrustOSM",356 tr("Check all available signatures for selected object."), this);357 signButton = new SideButton(marktr("Sign"), "sign", "TrustOSM",358 tr("Digital sign selected Tags, if you believe they are correct."), this);359 showButton = new SideButton(marktr("Show"), "showsig", "TrustOSM",360 tr("Show all available signatures for selected attribute."), this);361 362 createLayout(dataPanel, true, Arrays.asList(new SideButton[] {363 checkButton, signButton, showButton364 }));365 DataSet.addSelectionListener(this);366 }367 368 @Override369 public void actionPerformed(ActionEvent e) {370 String actionCommand = e.getActionCommand();371 if (actionCommand.equals("Check")) {372 for (OsmPrimitive osm : osmData) {373 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);374 if (TrustOSMplugin.signedItems.containsKey(id))375 TrustAnalyzer.checkEverything(TrustOSMplugin.signedItems.get(id));376 //checkedItems.put(osm, TrustOSMplugin.gpg.check(checkedItems.containsKey(osm)? checkedItems.get(osm) : new TrustOSMItem(osm)));377 }378 updateTable();379 geomTree.repaint();380 } else if (actionCommand.equals("Sign")) {381 for (int i : propertyTable.getSelectedRows()) {382 String key = (String)propertyTable.getValueAt(i, 0);383 for (OsmPrimitive osm : osmData) {384 if (osm.keySet().contains(key)) {385 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);386 TrustOsmPrimitive trust = TrustOSMplugin.signedItems.containsKey(id)? TrustOSMplugin.signedItems.get(id) : TrustOsmPrimitive.createTrustOsmPrimitive(osm);387 if (TrustOSMplugin.gpg.signTag(trust, key))388 TrustOSMplugin.signedItems.put(id, trust);389 }390 }391 }392 if (geomTree.getSelectionPaths()!=null)393 for (TreePath tp : geomTree.getSelectionPaths()) {394 Object o = ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject();395 if (o instanceof OsmPrimitive) {396 OsmPrimitive osm = (OsmPrimitive) o;397 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);398 if (osm instanceof Node) {399 Node osmNode = ((Node) osm);400 TrustNode trust = TrustOSMplugin.signedItems.containsKey(id)? (TrustNode) TrustOSMplugin.signedItems.get(id) : new TrustNode(osmNode);401 trust.storeNodeSig(TrustOSMplugin.gpg.signNode(osmNode));402 TrustOSMplugin.signedItems.put(id, trust);403 404 405 /*TreePath parentPath = tp.getParentPath();406 if (geomTree.isPathSelected(parentPath)) return;407 408 Node osmNode = ((Node) osm);409 if (((DefaultMutableTreeNode) parentPath.getLastPathComponent()).getUserObject() instanceof Way) {410 osm = (OsmPrimitive) ((DefaultMutableTreeNode) parentPath.getLastPathComponent()).getUserObject();411 id = String.valueOf(osm.getUniqueId());412 }413 TrustOsmPrimitive trust = TrustOSMplugin.signedItems.containsKey(id)? TrustOSMplugin.signedItems.get(id) : TrustOsmPrimitive.createTrustOsmPrimitive(osm);414 trust.storeNodeSig(osmNode, TrustOSMplugin.gpg.signNode(osm,osmNode));415 TrustOSMplugin.signedItems.put(id, trust);416 */417 } else if (osm instanceof Way) {418 TrustOSMplugin.signedItems.put(id, TrustOSMplugin.gpg.signWay(TrustOSMplugin.signedItems.containsKey(id)? (TrustWay)TrustOSMplugin.signedItems.get(id) : new TrustWay(osm)));419 /*Way osmWay = ((Way) osm);420 TrustWay trust = TrustOSMplugin.signedItems.containsKey(id)? (TrustWay) TrustOSMplugin.signedItems.get(id) : new TrustWay(osmWay);421 trust.storeSegmentSig(TrustOSMplugin.gpg.signWay(osmWay));422 TrustOSMplugin.signedItems.put(id, trust);423 */424 }425 } else if (o instanceof WaySegment) {426 TreePath parentPath = tp.getParentPath();427 if (geomTree.isPathSelected(parentPath)) return;428 WaySegment seg = (WaySegment) o;429 List<Node> nodes = new ArrayList<Node>();430 nodes.add(seg.getFirstNode());431 nodes.add(seg.getSecondNode());432 Way w = seg.way;433 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(w);434 TrustWay trust = TrustOSMplugin.signedItems.containsKey(id)? (TrustWay) TrustOSMplugin.signedItems.get(id) : new TrustWay(w);435 trust.storeSegmentSig(nodes,TrustOSMplugin.gpg.signSegment(trust,nodes));436 TrustOSMplugin.signedItems.put(id, trust);437 }438 }439 updateTable();440 geomTree.repaint();441 } else if (actionCommand.equals("Show")) {442 for (int i : propertyTable.getSelectedRows()) {443 String key = (String)propertyTable.getValueAt(i, 0);444 for (OsmPrimitive osm : osmData) {445 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);446 if (osm.keySet().contains(key) && TrustOSMplugin.signedItems.containsKey(id)) {447 TrustSignaturesDialog.showSignaturesDialog(TrustOSMplugin.signedItems.get(id), key);448 }449 }450 }451 if (geomTree.getSelectionPaths()!=null)452 for (TreePath tp : geomTree.getSelectionPaths()) {453 Object o = ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject();454 if (o instanceof OsmPrimitive) {455 OsmPrimitive osm = (OsmPrimitive) o;456 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);457 if (osm instanceof Node) {458 if (TrustOSMplugin.signedItems.containsKey(id)) {459 TrustSignaturesDialog.showSignaturesDialog((TrustNode) TrustOSMplugin.signedItems.get(id));460 }461 } else if (osm instanceof Way) {462 //TrustOSMplugin.signedItems.put(id, TrustOSMplugin.gpg.signGeometry(TrustOSMplugin.signedItems.containsKey(id)? TrustOSMplugin.signedItems.get(id) : new TrustOSMItem(osm)));463 }464 } else if (o instanceof WaySegment) {465 WaySegment seg = (WaySegment) o;466 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(seg.way);467 if (TrustOSMplugin.signedItems.containsKey(id)) {468 List<Node> nodes = new ArrayList<Node>();469 nodes.add(seg.getFirstNode());470 nodes.add(seg.getSecondNode());471 TrustSignaturesDialog.showSignaturesDialog((TrustWay) TrustOSMplugin.signedItems.get(id),nodes);472 }473 }474 }475 476 }477 }478 /*479 public void showSignaturesDialog(TrustOSMItem trust, String key) {480 TrustSignatures sigs;481 if ((sigs = trust.getSigsOnKey(key)) == null) {482 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Attribute."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE);483 } else {484 JPanel p = new JPanel();485 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));486 Dimension d = new Dimension(0,20);487 JLabel head = new JLabel(tr("Selected key value pair was:\n{0}={1}",key,trust.getOsmItem().get(key)));488 head.setAlignmentX(LEFT_ALIGNMENT);489 p.add(head);490 p.add(Box.createRigidArea(d));491 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss");492 for (PGPSignature s : sigs.getSignatures()) {493 JTextArea sigtext = new JTextArea(sigs.getArmoredFulltextSignature(s));494 sigtext.setEditable(false);495 sigtext.setAlignmentX(LEFT_ALIGNMENT);496 p.add(sigtext);497 JLabel siginfo = new JLabel(tr("Signature created at {0} by User {1}",formatter.format(s.getCreationTime()),s.getHashedSubPackets().getSignerUserID()));498 siginfo.setAlignmentX(LEFT_ALIGNMENT);499 p.add(siginfo);500 p.add(Box.createRigidArea(d));501 }502 503 JScrollPane scroller = new JScrollPane(p);504 JPanel content = new JPanel();505 content.setMaximumSize(new Dimension(600,500));506 content.add(scroller);507 JOptionPane.showMessageDialog(Main.parent,content, tr("Clearsigned Signature"), JOptionPane.PLAIN_MESSAGE);508 }509 }510 */511 public static List<WaySegment> generateSegmentListFromWay(Way w) {512 List<WaySegment> segList = new ArrayList<WaySegment>();513 for (int i = 0; i < w.getNodesCount()-1; i++) {514 segList.add(new WaySegment(w,i));515 }516 return segList;517 }518 519 private DefaultTreeModel createTree(){520 DefaultMutableTreeNode root = new DefaultMutableTreeNode();521 DefaultMutableTreeNode wayNode;522 if (osmData!=null)523 for (OsmPrimitive osm : osmData) {524 //String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);525 if(osm instanceof Node) {526 root.add(new DefaultMutableTreeNode(osm));527 } else if(osm instanceof Way) {528 wayNode = new DefaultMutableTreeNode(osm);529 List<WaySegment> presentSegments = TrustDialog.generateSegmentListFromWay(((Way)osm));530 for (WaySegment seg : presentSegments ) {531 wayNode.add(new DefaultMutableTreeNode(seg));532 }533 534 /*535 wayNode = new DefaultMutableTreeNode(osm);536 List<Node> presentNodes = ((Way)osm).getNodes();537 Iterator<Node> iter = presentNodes.iterator();538 while (iter.hasNext()) {539 wayNode.add(new DefaultMutableTreeNode(iter.next()));540 }541 542 if (TrustOSMplugin.signedItems.containsKey(id)) {543 TrustOsmPrimitive trust = TrustOSMplugin.signedItems.get(id);544 HashSet<Node> signedNodes = new HashSet<Node>(trust.getGeomSigs().keySet());545 signedNodes.removeAll(presentNodes);546 iter = signedNodes.iterator();547 Node removedNode;548 while (iter.hasNext()) {549 removedNode = iter.next();550 trust.updateNodeSigStatus(removedNode, TrustSignatures.ITEM_REMOVED);551 wayNode.add(new DefaultMutableTreeNode(removedNode));552 }553 }554 */555 root.add(wayNode);556 } else if(osm instanceof Relation) {557 558 }559 560 }561 562 return new DefaultTreeModel(root);563 564 }565 566 public void updateTable() {567 // re-load property data568 propertyData.setRowCount(0);569 570 Map<String, Map<String, Integer>> valueCount = new TreeMap<String, Map<String, Integer>>();571 572 TrustOsmPrimitive trust;573 574 valueCount.clear();575 rowStatus.clear();576 boolean sigsAvailable = false;577 578 for (OsmPrimitive osm : osmData) {579 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm);580 if (TrustOSMplugin.signedItems.containsKey(id)) {581 trust = TrustOSMplugin.signedItems.get(id);582 sigsAvailable = true;583 /*584 Map<String,String> tags = osm.getKeys();585 Map<String, TrustSignatures> signedTags = trust.getTagSigs();586 HashSet<String> removedKeys = new HashSet<String>(signedTags.keySet());587 removedKeys.removeAll(tags.keySet());588 for (String removedKey: removedKeys) {589 TrustSignatures sigs = signedTags.get(removedKey);590 sigs.setStatus( TrustSignatures.ITEM_REMOVED );591 String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(sigs.getOnePlainText());592 tags.put(kv[0],kv[1]);593 }594 */595 } else {596 trust = TrustOsmPrimitive.createTrustOsmPrimitive(osm);597 sigsAvailable = false;598 }599 600 //trust = TrustOSMplugin.signedItems.containsKey(osm) ? TrustOSMplugin.signedItems.get(osm) : new TrustOSMItem(osm);601 602 for (String key: osm.keySet()) {603 String value = osm.get(key);604 //keyCount.put(key, keyCount.containsKey(key) ? keyCount.get(key) + 1 : 1);605 606 byte status = sigsAvailable && trust.getTagSigs().containsKey(key) ? trust.getTagSigs().get(key).getStatus() : TrustSignatures.SIG_UNKNOWN ;607 Byte oldstatus = rowStatus.containsKey(key)? rowStatus.get(key) : new Byte(TrustSignatures.SIG_VALID);608 Byte sigstatus = new Byte(status);609 Byte newstatus;610 if (sigstatus.equals(new Byte(TrustSignatures.SIG_BROKEN)) || oldstatus.equals(new Byte(TrustSignatures.SIG_BROKEN))) {611 newstatus = new Byte(TrustSignatures.SIG_BROKEN);612 } else if (sigstatus.equals(new Byte(TrustSignatures.SIG_UNKNOWN)) || oldstatus.equals(new Byte(TrustSignatures.SIG_UNKNOWN))) {613 newstatus = new Byte(TrustSignatures.SIG_UNKNOWN);614 } else newstatus = new Byte(TrustSignatures.SIG_VALID);615 616 rowStatus.put(key, newstatus );617 if (valueCount.containsKey(key)) {618 Map<String, Integer> v = valueCount.get(key);619 v.put(value, v.containsKey(value)? v.get(value) + 1 : 1 );620 } else {621 TreeMap<String,Integer> v = new TreeMap<String, Integer>();622 v.put(value, 1);623 valueCount.put(key, v);624 }625 }626 }627 for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) {628 int count=0;629 for (Entry<String, Integer> e1: e.getValue().entrySet()) {630 count+=e1.getValue();631 }632 if (count < osmData.size()) {633 e.getValue().put("", osmData.size()-count);634 }635 propertyData.addRow(new Object[]{e.getKey(), e.getValue()});636 }637 638 639 boolean hasSelection = !osmData.isEmpty();640 boolean hasTags = hasSelection && propertyData.getRowCount() > 0;641 642 propertyTable.setVisible(hasTags);643 propertyTable.getTableHeader().setVisible(hasTags);644 }645 646 @Override647 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {648 this.osmData = newSelection;649 650 if (!isVisible())651 return;652 geomTree.setModel(createTree());653 updateTable();654 //signButton.setEnabled(newSelection.size() == 1);655 }656 657 @Override658 public void paint(Graphics2D g, MapView mv, Bounds bbox) {659 // if there are no Segments to highlight - return660 if (selectedSegments.isEmpty()) return;661 662 // sanity checks663 if (Main.map.mapView == null) return;664 665 666 Graphics2D g2 = g;667 g2.setColor(PaintColors.HIGHLIGHT.get());668 g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));669 670 // highlight all selected WaySegments671 for (WaySegment seg : selectedSegments) {672 GeneralPath b = new GeneralPath();673 Point p1=mv.getPoint(seg.getFirstNode());674 Point p2=mv.getPoint(seg.getSecondNode());675 676 b.moveTo(p1.x,p1.y); b.lineTo(p2.x, p2.y);677 678 g2.draw(b);679 }680 g2.setStroke(new BasicStroke(1));681 }72 /** 73 * 74 */ 75 private static final long serialVersionUID = -3324984194315776740L; 76 77 78 public final static Color BGCOLOR_NO_SIG = new Color(234, 234, 234); 79 // public final static Color BGCOLOR_VALID_SIG = new Color(235,255,177); 80 public final static Color BGCOLOR_VALID_SIG = new Color(74,245,106); 81 public final static Color BGCOLOR_BROKEN_SIG = new Color(255, 197, 197); 82 public final static Color BGCOLOR_REMOVED_ITEM = new Color(255, 100, 100); 83 public final static Color BGCOLOR_UPDATED_ITEM = new Color(249,221,95); 84 85 86 /** Use a TrustGPGPreparer to sign or validate signatures */ 87 //private final TrustGPGPreparer gpg; 88 89 /** The check signatures button */ 90 private final SideButton checkButton; 91 92 /** The sign button */ 93 private final SideButton signButton; 94 95 /** The show sigs button */ 96 private final SideButton showButton; 97 98 private final Map<String, Byte> rowStatus = new HashMap<>(); 99 100 /** The selected osmData */ 101 private Collection<? extends OsmPrimitive> osmData; 102 103 104 private final List<WaySegment> selectedSegments = new ArrayList<>(); 105 private final List<OsmPrimitive> selectedPrimitives = new ArrayList<>(); 106 107 /** The JTree for showing the geometry */ 108 private final JTree geomTree; 109 110 111 /** 112 * The property data. 113 */ 114 private final DefaultTableModel propertyData = new DefaultTableModel() { 115 /** 116 * 117 */ 118 private static final long serialVersionUID = -1252801283184909691L; 119 @Override public boolean isCellEditable(int row, int column) { 120 return false; 121 } 122 @Override public Class<?> getColumnClass(int columnIndex) { 123 return String.class; 124 } 125 }; 126 private final JTable propertyTable = new JTable(propertyData) { 127 /** 128 * 129 */ 130 private static final long serialVersionUID = 1L; 131 132 @Override 133 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { 134 Component c = super.prepareRenderer(renderer, row, column); 135 Byte stat = rowStatus.get(getModel().getValueAt(row, 0)); 136 if (!isRowSelected(row)) 137 switch (stat.byteValue()) { 138 case -2: c.setBackground( BGCOLOR_REMOVED_ITEM ); break; 139 case -1: c.setBackground( BGCOLOR_BROKEN_SIG ); break; 140 case 1: c.setBackground( BGCOLOR_VALID_SIG ); break; 141 default: c.setBackground( BGCOLOR_NO_SIG ); break; 142 } 143 return c; 144 } 145 }; 146 147 /** The JTable for members of a relation */ 148 private final DefaultTableModel memberData = new DefaultTableModel() { 149 150 /** 151 * 152 */ 153 private static final long serialVersionUID = 1L; 154 @Override public boolean isCellEditable(int row, int column) { 155 return false; 156 } 157 @Override public Class<?> getColumnClass(int columnIndex) { 158 return String.class; 159 } 160 }; 161 private final JTable memberTable = new JTable(memberData) { 162 /** 163 * 164 */ 165 private static final long serialVersionUID = 1L; 166 167 @Override 168 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { 169 Component c = super.prepareRenderer(renderer, row, column); 170 Byte stat = rowStatus.get(getModel().getValueAt(row, 0)); 171 if (!isRowSelected(row)) 172 switch (stat.byteValue()) { 173 case -2: c.setBackground( BGCOLOR_REMOVED_ITEM ); break; 174 case -1: c.setBackground( BGCOLOR_BROKEN_SIG ); break; 175 case 1: c.setBackground( BGCOLOR_VALID_SIG ); break; 176 default: c.setBackground( BGCOLOR_NO_SIG ); break; 177 } 178 return c; 179 } 180 }; 181 182 183 /** 184 * Constructor 185 */ 186 public TrustDialog() { 187 super(tr("Object signatures"), "trustosm", tr("Open object signing window."), 188 Shortcut.registerShortcut("subwindow:trustosm", tr("Toggle: {0}", tr("Object signatures")), 189 KeyEvent.VK_T, Shortcut.ALT_CTRL), 150); 190 191 Main.map.mapView.addTemporaryLayer(this); 192 193 // setting up the properties table 194 propertyData.setColumnIdentifiers(new String[]{tr("Key"),tr("Value")}); 195 196 // copy and paste from org.openstreetmap.josm.gui.dialogs.properties.PropertiesDialog 197 198 propertyTable.getColumnModel().getColumn(1).setCellRenderer(new DefaultTableCellRenderer(){ 199 /** 200 * 201 */ 202 private static final long serialVersionUID = 8003207668070727861L; 203 204 @Override 205 public Component getTableCellRendererComponent(JTable table, Object value, 206 boolean isSelected, boolean hasFocus, int row, int column) { 207 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column); 208 if (c instanceof JLabel) { 209 String str = null; 210 if (value instanceof String) { 211 str = (String) value; 212 } else if (value instanceof Map<?, ?>) { 213 Map<?, ?> v = (Map<?, ?>) value; 214 if (v.size() != 1) { 215 str=tr("<different>"); 216 c.setFont(c.getFont().deriveFont(Font.ITALIC)); 217 } else { 218 final Map.Entry<?, ?> entry = v.entrySet().iterator().next(); 219 str = (String) entry.getKey(); 220 } 221 } 222 ((JLabel)c).setText(str); 223 } 224 return c; 225 } 226 }); 227 228 geomTree = new JTree( createTree() ); 229 230 geomTree.setBackground( BGCOLOR_NO_SIG ); 231 geomTree.setRootVisible(false); 232 geomTree.setCellRenderer(new DefaultTreeCellRenderer(){ 233 234 /** 235 * 236 */ 237 private static final long serialVersionUID = -3070210847060314196L; 238 239 @Override 240 public Component getTreeCellRendererComponent(JTree tree, Object value, 241 boolean selected, boolean expanded, boolean leaf, int row, 242 boolean hasFocus) 243 { 244 super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); 245 246 DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; 247 if (node.isRoot()) return this; 248 setBackgroundNonSelectionColor( BGCOLOR_NO_SIG ); 249 Object o = node.getUserObject(); 250 if (o instanceof OsmPrimitive){ 251 OsmPrimitive osm = (OsmPrimitive) o; 252 setIcon(ImageProvider.get(OsmPrimitiveType.from(osm))); 253 setText(osm.getDisplayName(DefaultNameFormatter.getInstance())); 254 255 256 if (osm instanceof Node) { 257 Node osmNode = (Node) osm; 258 TrustSignatures sigs; 259 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 260 if (TrustOSMplugin.signedItems.containsKey(id) && (sigs = ((TrustNode)TrustOSMplugin.signedItems.get(id)).getNodeSigs()) != null) { 261 byte stat = sigs.getStatus(); 262 switch (stat) { 263 case -2: setBackgroundNonSelectionColor( BGCOLOR_REMOVED_ITEM ); break; 264 case -1: setBackgroundNonSelectionColor( BGCOLOR_BROKEN_SIG ); break; 265 case 1: setBackgroundNonSelectionColor( BGCOLOR_VALID_SIG ); break; 266 default: setBackgroundNonSelectionColor( BGCOLOR_NO_SIG ); break; 267 } 268 } 269 } else if (osm instanceof Way) { 270 //setBackgroundNonSelectionColor( BGCOLOR_NO_SIG ); 271 } 272 273 } else if (o instanceof WaySegment){ 274 WaySegment seg = (WaySegment) o; 275 setIcon(ImageProvider.get("mapmode/addsegment")); 276 setText(seg.getFirstNode().getDisplayName(DefaultNameFormatter.getInstance()) + " ----- " + seg.getSecondNode().getDisplayName(DefaultNameFormatter.getInstance())); 277 TrustSignatures sigs; 278 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(seg.way); 279 if (TrustOSMplugin.signedItems.containsKey(id) && (sigs = ((TrustWay)TrustOSMplugin.signedItems.get(id)).getSigsOnSegment(seg)) != null) { 280 byte stat = sigs.getStatus(); 281 switch (stat) { 282 case -2: setBackgroundNonSelectionColor( BGCOLOR_REMOVED_ITEM ); break; 283 case -1: setBackgroundNonSelectionColor( BGCOLOR_BROKEN_SIG ); break; 284 case 1: setBackgroundNonSelectionColor( BGCOLOR_VALID_SIG ); break; 285 default: setBackgroundNonSelectionColor( BGCOLOR_NO_SIG ); break; 286 } 287 } 288 } 289 return this; 290 } 291 292 293 }); 294 295 geomTree.addTreeSelectionListener(new TreeSelectionListener() { 296 public void valueChanged(TreeSelectionEvent e) { 297 // unhighlight everything 298 for (OsmPrimitive p : selectedPrimitives) { 299 p.setHighlighted(false); 300 } 301 selectedPrimitives.clear(); 302 selectedSegments.clear(); 303 if (geomTree.getSelectionPaths()!=null) 304 for (TreePath tp : geomTree.getSelectionPaths()) { 305 Object o = ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject(); 306 if (o instanceof WaySegment) { 307 selectedSegments.add((WaySegment) o); 308 } else if (o instanceof OsmPrimitive) { 309 OsmPrimitive highlight = (OsmPrimitive) o; 310 highlight.setHighlighted(true); 311 selectedPrimitives.add(highlight); 312 } 313 } 314 Main.map.mapView.repaint(); 315 } 316 }); 317 318 propertyTable.addFocusListener(new FocusListener(){ 319 320 @Override 321 public void focusGained(FocusEvent fe) { 322 geomTree.clearSelection(); 323 324 } 325 326 @Override 327 public void focusLost(FocusEvent fe) { 328 329 } 330 331 }); 332 333 geomTree.addFocusListener(new FocusListener(){ 334 335 @Override 336 public void focusGained(FocusEvent fe) { 337 propertyTable.clearSelection(); 338 339 } 340 341 @Override 342 public void focusLost(FocusEvent fe) { 343 344 } 345 346 }); 347 348 JPanel dataPanel = new JPanel(); 349 dataPanel.setLayout(new BoxLayout(dataPanel, BoxLayout.PAGE_AXIS)); 350 propertyTable.setAlignmentX(LEFT_ALIGNMENT); 351 dataPanel.add(propertyTable); 352 geomTree.setAlignmentX(LEFT_ALIGNMENT); 353 dataPanel.add(geomTree); 354 355 checkButton = new SideButton(marktr("Check"), "checksignatures", "TrustOSM", 356 tr("Check all available signatures for selected object."), this); 357 signButton = new SideButton(marktr("Sign"), "sign", "TrustOSM", 358 tr("Digital sign selected Tags, if you believe they are correct."), this); 359 showButton = new SideButton(marktr("Show"), "showsig", "TrustOSM", 360 tr("Show all available signatures for selected attribute."), this); 361 362 createLayout(dataPanel, true, Arrays.asList(new SideButton[] { 363 checkButton, signButton, showButton 364 })); 365 DataSet.addSelectionListener(this); 366 } 367 368 @Override 369 public void actionPerformed(ActionEvent e) { 370 String actionCommand = e.getActionCommand(); 371 if (actionCommand.equals("Check")) { 372 for (OsmPrimitive osm : osmData) { 373 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 374 if (TrustOSMplugin.signedItems.containsKey(id)) 375 TrustAnalyzer.checkEverything(TrustOSMplugin.signedItems.get(id)); 376 //checkedItems.put(osm, TrustOSMplugin.gpg.check(checkedItems.containsKey(osm)? checkedItems.get(osm) : new TrustOSMItem(osm))); 377 } 378 updateTable(); 379 geomTree.repaint(); 380 } else if (actionCommand.equals("Sign")) { 381 for (int i : propertyTable.getSelectedRows()) { 382 String key = (String)propertyTable.getValueAt(i, 0); 383 for (OsmPrimitive osm : osmData) { 384 if (osm.keySet().contains(key)) { 385 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 386 TrustOsmPrimitive trust = TrustOSMplugin.signedItems.containsKey(id)? TrustOSMplugin.signedItems.get(id) : TrustOsmPrimitive.createTrustOsmPrimitive(osm); 387 if (TrustOSMplugin.gpg.signTag(trust, key)) 388 TrustOSMplugin.signedItems.put(id, trust); 389 } 390 } 391 } 392 if (geomTree.getSelectionPaths()!=null) 393 for (TreePath tp : geomTree.getSelectionPaths()) { 394 Object o = ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject(); 395 if (o instanceof OsmPrimitive) { 396 OsmPrimitive osm = (OsmPrimitive) o; 397 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 398 if (osm instanceof Node) { 399 Node osmNode = ((Node) osm); 400 TrustNode trust = TrustOSMplugin.signedItems.containsKey(id)? (TrustNode) TrustOSMplugin.signedItems.get(id) : new TrustNode(osmNode); 401 trust.storeNodeSig(TrustOSMplugin.gpg.signNode(osmNode)); 402 TrustOSMplugin.signedItems.put(id, trust); 403 404 405 /* TreePath parentPath = tp.getParentPath(); 406 if (geomTree.isPathSelected(parentPath)) return; 407 408 Node osmNode = ((Node) osm); 409 if (((DefaultMutableTreeNode) parentPath.getLastPathComponent()).getUserObject() instanceof Way) { 410 osm = (OsmPrimitive) ((DefaultMutableTreeNode) parentPath.getLastPathComponent()).getUserObject(); 411 id = String.valueOf(osm.getUniqueId()); 412 } 413 TrustOsmPrimitive trust = TrustOSMplugin.signedItems.containsKey(id)? TrustOSMplugin.signedItems.get(id) : TrustOsmPrimitive.createTrustOsmPrimitive(osm); 414 trust.storeNodeSig(osmNode, TrustOSMplugin.gpg.signNode(osm,osmNode)); 415 TrustOSMplugin.signedItems.put(id, trust); 416 */ 417 } else if (osm instanceof Way) { 418 TrustOSMplugin.signedItems.put(id, TrustOSMplugin.gpg.signWay(TrustOSMplugin.signedItems.containsKey(id)? (TrustWay)TrustOSMplugin.signedItems.get(id) : new TrustWay(osm))); 419 /*Way osmWay = ((Way) osm); 420 TrustWay trust = TrustOSMplugin.signedItems.containsKey(id)? (TrustWay) TrustOSMplugin.signedItems.get(id) : new TrustWay(osmWay); 421 trust.storeSegmentSig(TrustOSMplugin.gpg.signWay(osmWay)); 422 TrustOSMplugin.signedItems.put(id, trust); 423 */ 424 } 425 } else if (o instanceof WaySegment) { 426 TreePath parentPath = tp.getParentPath(); 427 if (geomTree.isPathSelected(parentPath)) return; 428 WaySegment seg = (WaySegment) o; 429 List<Node> nodes = new ArrayList<>(); 430 nodes.add(seg.getFirstNode()); 431 nodes.add(seg.getSecondNode()); 432 Way w = seg.way; 433 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(w); 434 TrustWay trust = TrustOSMplugin.signedItems.containsKey(id)? (TrustWay) TrustOSMplugin.signedItems.get(id) : new TrustWay(w); 435 trust.storeSegmentSig(nodes,TrustOSMplugin.gpg.signSegment(trust,nodes)); 436 TrustOSMplugin.signedItems.put(id, trust); 437 } 438 } 439 updateTable(); 440 geomTree.repaint(); 441 } else if (actionCommand.equals("Show")) { 442 for (int i : propertyTable.getSelectedRows()) { 443 String key = (String)propertyTable.getValueAt(i, 0); 444 for (OsmPrimitive osm : osmData) { 445 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 446 if (osm.keySet().contains(key) && TrustOSMplugin.signedItems.containsKey(id)) { 447 TrustSignaturesDialog.showSignaturesDialog(TrustOSMplugin.signedItems.get(id), key); 448 } 449 } 450 } 451 if (geomTree.getSelectionPaths()!=null) 452 for (TreePath tp : geomTree.getSelectionPaths()) { 453 Object o = ((DefaultMutableTreeNode) tp.getLastPathComponent()).getUserObject(); 454 if (o instanceof OsmPrimitive) { 455 OsmPrimitive osm = (OsmPrimitive) o; 456 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 457 if (osm instanceof Node) { 458 if (TrustOSMplugin.signedItems.containsKey(id)) { 459 TrustSignaturesDialog.showSignaturesDialog((TrustNode) TrustOSMplugin.signedItems.get(id)); 460 } 461 } else if (osm instanceof Way) { 462 //TrustOSMplugin.signedItems.put(id, TrustOSMplugin.gpg.signGeometry(TrustOSMplugin.signedItems.containsKey(id)? TrustOSMplugin.signedItems.get(id) : new TrustOSMItem(osm))); 463 } 464 } else if (o instanceof WaySegment) { 465 WaySegment seg = (WaySegment) o; 466 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(seg.way); 467 if (TrustOSMplugin.signedItems.containsKey(id)) { 468 List<Node> nodes = new ArrayList<>(); 469 nodes.add(seg.getFirstNode()); 470 nodes.add(seg.getSecondNode()); 471 TrustSignaturesDialog.showSignaturesDialog((TrustWay) TrustOSMplugin.signedItems.get(id),nodes); 472 } 473 } 474 } 475 476 } 477 } 478 /* 479 public void showSignaturesDialog(TrustOSMItem trust, String key) { 480 TrustSignatures sigs; 481 if ((sigs = trust.getSigsOnKey(key)) == null) { 482 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Attribute."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE); 483 } else { 484 JPanel p = new JPanel(); 485 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); 486 Dimension d = new Dimension(0,20); 487 JLabel head = new JLabel(tr("Selected key value pair was:\n{0}={1}",key,trust.getOsmItem().get(key))); 488 head.setAlignmentX(LEFT_ALIGNMENT); 489 p.add(head); 490 p.add(Box.createRigidArea(d)); 491 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss"); 492 for (PGPSignature s : sigs.getSignatures()) { 493 JTextArea sigtext = new JTextArea(sigs.getArmoredFulltextSignature(s)); 494 sigtext.setEditable(false); 495 sigtext.setAlignmentX(LEFT_ALIGNMENT); 496 p.add(sigtext); 497 JLabel siginfo = new JLabel(tr("Signature created at {0} by User {1}",formatter.format(s.getCreationTime()),s.getHashedSubPackets().getSignerUserID())); 498 siginfo.setAlignmentX(LEFT_ALIGNMENT); 499 p.add(siginfo); 500 p.add(Box.createRigidArea(d)); 501 } 502 503 JScrollPane scroller = new JScrollPane(p); 504 JPanel content = new JPanel(); 505 content.setMaximumSize(new Dimension(600,500)); 506 content.add(scroller); 507 JOptionPane.showMessageDialog(Main.parent,content, tr("Clearsigned Signature"), JOptionPane.PLAIN_MESSAGE); 508 } 509 } 510 */ 511 public static List<WaySegment> generateSegmentListFromWay(Way w) { 512 List<WaySegment> segList = new ArrayList<>(); 513 for (int i = 0; i < w.getNodesCount()-1; i++) { 514 segList.add(new WaySegment(w,i)); 515 } 516 return segList; 517 } 518 519 private DefaultTreeModel createTree(){ 520 DefaultMutableTreeNode root = new DefaultMutableTreeNode(); 521 DefaultMutableTreeNode wayNode; 522 if (osmData!=null) 523 for (OsmPrimitive osm : osmData) { 524 //String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 525 if(osm instanceof Node) { 526 root.add(new DefaultMutableTreeNode(osm)); 527 } else if(osm instanceof Way) { 528 wayNode = new DefaultMutableTreeNode(osm); 529 List<WaySegment> presentSegments = TrustDialog.generateSegmentListFromWay(((Way)osm)); 530 for (WaySegment seg : presentSegments ) { 531 wayNode.add(new DefaultMutableTreeNode(seg)); 532 } 533 534 /* 535 wayNode = new DefaultMutableTreeNode(osm); 536 List<Node> presentNodes = ((Way)osm).getNodes(); 537 Iterator<Node> iter = presentNodes.iterator(); 538 while (iter.hasNext()) { 539 wayNode.add(new DefaultMutableTreeNode(iter.next())); 540 } 541 542 if (TrustOSMplugin.signedItems.containsKey(id)) { 543 TrustOsmPrimitive trust = TrustOSMplugin.signedItems.get(id); 544 HashSet<Node> signedNodes = new HashSet<Node>(trust.getGeomSigs().keySet()); 545 signedNodes.removeAll(presentNodes); 546 iter = signedNodes.iterator(); 547 Node removedNode; 548 while (iter.hasNext()) { 549 removedNode = iter.next(); 550 trust.updateNodeSigStatus(removedNode, TrustSignatures.ITEM_REMOVED); 551 wayNode.add(new DefaultMutableTreeNode(removedNode)); 552 } 553 } 554 */ 555 root.add(wayNode); 556 } else if(osm instanceof Relation) { 557 558 } 559 560 } 561 562 return new DefaultTreeModel(root); 563 564 } 565 566 public void updateTable() { 567 // re-load property data 568 propertyData.setRowCount(0); 569 570 Map<String, Map<String, Integer>> valueCount = new TreeMap<>(); 571 572 TrustOsmPrimitive trust; 573 574 valueCount.clear(); 575 rowStatus.clear(); 576 boolean sigsAvailable = false; 577 578 for (OsmPrimitive osm : osmData) { 579 String id = TrustOsmPrimitive.createUniqueObjectIdentifier(osm); 580 if (TrustOSMplugin.signedItems.containsKey(id)) { 581 trust = TrustOSMplugin.signedItems.get(id); 582 sigsAvailable = true; 583 /* 584 Map<String,String> tags = osm.getKeys(); 585 Map<String, TrustSignatures> signedTags = trust.getTagSigs(); 586 HashSet<String> removedKeys = new HashSet<String>(signedTags.keySet()); 587 removedKeys.removeAll(tags.keySet()); 588 for (String removedKey: removedKeys) { 589 TrustSignatures sigs = signedTags.get(removedKey); 590 sigs.setStatus( TrustSignatures.ITEM_REMOVED ); 591 String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(sigs.getOnePlainText()); 592 tags.put(kv[0],kv[1]); 593 } 594 */ 595 } else { 596 trust = TrustOsmPrimitive.createTrustOsmPrimitive(osm); 597 sigsAvailable = false; 598 } 599 600 // trust = TrustOSMplugin.signedItems.containsKey(osm) ? TrustOSMplugin.signedItems.get(osm) : new TrustOSMItem(osm); 601 602 for (String key: osm.keySet()) { 603 String value = osm.get(key); 604 //keyCount.put(key, keyCount.containsKey(key) ? keyCount.get(key) + 1 : 1); 605 606 byte status = sigsAvailable && trust.getTagSigs().containsKey(key) ? trust.getTagSigs().get(key).getStatus() : TrustSignatures.SIG_UNKNOWN ; 607 Byte oldstatus = rowStatus.containsKey(key)? rowStatus.get(key) : new Byte(TrustSignatures.SIG_VALID); 608 Byte sigstatus = new Byte(status); 609 Byte newstatus; 610 if (sigstatus.equals(new Byte(TrustSignatures.SIG_BROKEN)) || oldstatus.equals(new Byte(TrustSignatures.SIG_BROKEN))) { 611 newstatus = new Byte(TrustSignatures.SIG_BROKEN); 612 } else if (sigstatus.equals(new Byte(TrustSignatures.SIG_UNKNOWN)) || oldstatus.equals(new Byte(TrustSignatures.SIG_UNKNOWN))) { 613 newstatus = new Byte(TrustSignatures.SIG_UNKNOWN); 614 } else newstatus = new Byte(TrustSignatures.SIG_VALID); 615 616 rowStatus.put(key, newstatus ); 617 if (valueCount.containsKey(key)) { 618 Map<String, Integer> v = valueCount.get(key); 619 v.put(value, v.containsKey(value)? v.get(value) + 1 : 1 ); 620 } else { 621 TreeMap<String,Integer> v = new TreeMap<>(); 622 v.put(value, 1); 623 valueCount.put(key, v); 624 } 625 } 626 } 627 for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) { 628 int count=0; 629 for (Entry<String, Integer> e1: e.getValue().entrySet()) { 630 count+=e1.getValue(); 631 } 632 if (count < osmData.size()) { 633 e.getValue().put("", osmData.size()-count); 634 } 635 propertyData.addRow(new Object[]{e.getKey(), e.getValue()}); 636 } 637 638 639 boolean hasSelection = !osmData.isEmpty(); 640 boolean hasTags = hasSelection && propertyData.getRowCount() > 0; 641 642 propertyTable.setVisible(hasTags); 643 propertyTable.getTableHeader().setVisible(hasTags); 644 } 645 646 @Override 647 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 648 this.osmData = newSelection; 649 650 if (!isVisible()) 651 return; 652 geomTree.setModel(createTree()); 653 updateTable(); 654 // signButton.setEnabled(newSelection.size() == 1); 655 } 656 657 @Override 658 public void paint(Graphics2D g, MapView mv, Bounds bbox) { 659 // if there are no Segments to highlight - return 660 if (selectedSegments.isEmpty()) return; 661 662 // sanity checks 663 if (Main.map.mapView == null) return; 664 665 666 Graphics2D g2 = g; 667 g2.setColor(PaintColors.HIGHLIGHT.get()); 668 g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); 669 670 // highlight all selected WaySegments 671 for (WaySegment seg : selectedSegments) { 672 GeneralPath b = new GeneralPath(); 673 Point p1=mv.getPoint(seg.getFirstNode()); 674 Point p2=mv.getPoint(seg.getSecondNode()); 675 676 b.moveTo(p1.x,p1.y); b.lineTo(p2.x, p2.y); 677 678 g2.draw(b); 679 } 680 g2.setStroke(new BasicStroke(1)); 681 } 682 682 683 683 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/TrustPreferenceEditor.java
r26054 r30724 23 23 public class TrustPreferenceEditor implements PreferenceSetting { 24 24 25 private final JCheckBox showSignedDeleted = new JCheckBox(tr("Show deleted tags and notes if they were signed before"));26 private final JRadioButton defaultHomedir = new JRadioButton(tr("Use default (and maybe existing) GnuPG directory ({0}) to store new keys and configs.", "~/.gnupg"));27 private final JRadioButton separateHomedir = new JRadioButton(tr("Use separate GnuPG directory ({0}) to store new keys and configs.", TrustOSMplugin.getGpgPath()));25 private final JCheckBox showSignedDeleted = new JCheckBox(tr("Show deleted tags and notes if they were signed before")); 26 private final JRadioButton defaultHomedir = new JRadioButton(tr("Use default (and maybe existing) GnuPG directory ({0}) to store new keys and configs.", "~/.gnupg")); 27 private final JRadioButton separateHomedir = new JRadioButton(tr("Use separate GnuPG directory ({0}) to store new keys and configs.", TrustOSMplugin.getGpgPath())); 28 28 29 @Override30 public void addGui(final PreferenceTabbedPane gui) {31 // TODO Auto-generated method stub32 JPanel p = gui.createPreferenceTab("trustosm", tr("Trust OSM Settings"), tr("Change GPG and privacy settings of the trustosm plugin."));33 JTabbedPane tabs = new JTabbedPane();34 p.add(tabs, GBC.eol().fill(GBC.BOTH));29 @Override 30 public void addGui(final PreferenceTabbedPane gui) { 31 // TODO Auto-generated method stub 32 JPanel p = gui.createPreferenceTab("trustosm", tr("Trust OSM Settings"), tr("Change GPG and privacy settings of the trustosm plugin.")); 33 JTabbedPane tabs = new JTabbedPane(); 34 p.add(tabs, GBC.eol().fill(GBC.BOTH)); 35 35 36 36 37 JPanel gpgsettings = new JPanel(new GridBagLayout());37 JPanel gpgsettings = new JPanel(new GridBagLayout()); 38 38 39 gpgsettings.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));39 gpgsettings.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 40 40 41 gpgsettings.add(new JLabel(tr("Use separate GnuPG configuration directory?")), GBC.eol().insets(20,0,0,0));42 ButtonGroup gpgdirGroup = new ButtonGroup();43 gpgdirGroup.add(separateHomedir);44 gpgdirGroup.add(defaultHomedir);41 gpgsettings.add(new JLabel(tr("Use separate GnuPG configuration directory?")), GBC.eol().insets(20,0,0,0)); 42 ButtonGroup gpgdirGroup = new ButtonGroup(); 43 gpgdirGroup.add(separateHomedir); 44 gpgdirGroup.add(defaultHomedir); 45 45 46 if (Main.pref.getBoolean("trustosm.gpg.separateHomedir")) {47 separateHomedir.setSelected(true);48 } else49 defaultHomedir.setSelected(true);46 if (Main.pref.getBoolean("trustosm.gpg.separateHomedir")) { 47 separateHomedir.setSelected(true); 48 } else 49 defaultHomedir.setSelected(true); 50 50 51 gpgsettings.add(separateHomedir, GBC.eol().insets(40,0,0,0));52 gpgsettings.add(defaultHomedir, GBC.eol().insets(40,0,0,0));51 gpgsettings.add(separateHomedir, GBC.eol().insets(40,0,0,0)); 52 gpgsettings.add(defaultHomedir, GBC.eol().insets(40,0,0,0)); 53 53 54 54 55 gpgsettings.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.BOTH));56 JScrollPane scrollpane = new JScrollPane(gpgsettings);57 scrollpane.setBorder(BorderFactory.createEmptyBorder( 0, 0, 0, 0 ));58 tabs.add(tr("GnuPG"), scrollpane);55 gpgsettings.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.BOTH)); 56 JScrollPane scrollpane = new JScrollPane(gpgsettings); 57 scrollpane.setBorder(BorderFactory.createEmptyBorder( 0, 0, 0, 0 )); 58 tabs.add(tr("GnuPG"), scrollpane); 59 59 60 60 61 JPanel dialogsettings = new JPanel(new GridBagLayout());62 tabs.add(tr("Dialog"), dialogsettings);63 dialogsettings.add(showSignedDeleted, GBC.eol().fill(GBC.HORIZONTAL).insets(20,0,0,5));61 JPanel dialogsettings = new JPanel(new GridBagLayout()); 62 tabs.add(tr("Dialog"), dialogsettings); 63 dialogsettings.add(showSignedDeleted, GBC.eol().fill(GBC.HORIZONTAL).insets(20,0,0,5)); 64 64 65 }65 } 66 66 67 @Override68 public boolean ok() {69 Main.pref.put("trustosm.gpg.showSignedDeleted", showSignedDeleted.isSelected());70 Main.pref.put("trustosm.gpg.separateHomedir", separateHomedir.isSelected());71 //TrustOSMplugin.gpg.refreshGpg();72 return false;73 }67 @Override 68 public boolean ok() { 69 Main.pref.put("trustosm.gpg.showSignedDeleted", showSignedDeleted.isSelected()); 70 Main.pref.put("trustosm.gpg.separateHomedir", separateHomedir.isSelected()); 71 // TrustOSMplugin.gpg.refreshGpg(); 72 return false; 73 } 74 74 75 75 -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/gui/dialogs/TrustSignaturesDialog.java
r25269 r30724 7 7 import java.awt.event.MouseAdapter; 8 8 import java.awt.event.MouseEvent; 9 import java.text.SimpleDateFormat;10 9 import java.util.List; 11 10 … … 41 40 42 41 43 private static String createLabel(String plain, int type) {44 if (type == 0) {45 String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(plain);46 return tr("Signed key value pair was: {0}={1}", kv[0],kv[1]);47 } else if (type == 1) {48 Node node = TrustNode.generateNodeFromSigtext(plain);49 //return tr("Signed node was: {0}", node.getDisplayName(DefaultNameFormatter.getInstance()));50 return "ID:"+node.getUniqueId()+" ("+node.getCoor().toString() + ")";51 } else if (type == 2) {52 List<Node> nodes = TrustWay.generateSegmentFromSigtext(plain);53 return "From:"+nodes.get(0).getUniqueId()+", To:"+nodes.get(nodes.size()-1).getUniqueId();54 }55 return "No known type";56 }57 58 private static void showDialog(TrustSignatures sigs, String label, int type) {59 JPanel p = new JPanel(new GridBagLayout());60 p.add(new JLabel(label),GBC.eol());61 62 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss");63 64 for (String plain : sigs.getAllPlainTexts()) {65 JTextArea sigtext = new JTextArea(sigs.getArmoredFulltextSignatureAll(plain));66 sigtext.setEditable(false);67 JPanel textcontent = new JPanel();68 textcontent.add(sigtext);69 70 p.add(new JCollapsiblePanel(createLabel(plain, type),textcontent),GBC.eol());71 72 List<PGPSignature> siglist = sigs.getSignaturesByPlaintext(plain);73 JPanel signerPanel = new JPanel(new GridBagLayout());74 //signerPanel.add(createSignerTree(siglist));75 KeyTreeTableModel km = new KeyTreeTableModel(siglist);76 final JXTreeTable t = new JXTreeTable( km );77 //t.setHorizontalScrollEnabled(true);78 //t.setRootVisible(false);79 t.addMouseListener(new MouseAdapter() {80 @Override81 public void mouseClicked(MouseEvent e) {82 if (e.getClickCount() == 2) {83 TreePath selPath = t.getPathForLocation(e.getX(), e.getY());84 if (selPath == null)85 return;86 SignatureTreeNode sn = (SignatureTreeNode)selPath.getLastPathComponent();87 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(sn.getSignature().getKeyID());88 TrustGPG.showKeyDetails(pub);89 }90 }91 });92 t.setLeafIcon(ImageProvider.get("dialogs/sign"));93 t.setOpenIcon(ImageProvider.get("dialogs/sign_color"));94 t.setClosedIcon(ImageProvider.get("dialogs/sign_color"));95 t.expandAll();96 t.packAll();97 t.collapseAll();98 signerPanel.add(new JScrollPane(t));99 100 101 //JTreeTable tt = new JTreeTable();102 103 /*for (PGPSignature s : siglist) {104 signerPanel.add(createKeyButton(tr("Signature created at {0} by User {1}",formatter.format(s.getCreationTime()),s.getHashedSubPackets().getSignerUserID()),s.getKeyID()),GBC.eol());105 //signerPanel.add(new JLabel(tr("Signature created at {0} by User {1}",formatter.format(s.getCreationTime()),s.getHashedSubPackets().getSignerUserID())),GBC.eol());106 }*/107 108 p.add(new JCollapsiblePanel(tr("{0} Signatures found.", siglist.size()),signerPanel),GBC.eol().insets(20,0,0,0));109 }110 p.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.BOTH));111 JScrollPane scroller = new JScrollPane(p);112 //JPanel content = new JPanel();113 scroller.setPreferredSize(new Dimension(700,500));114 //content.add(scroller);115 //JOptionPane.showMessageDialog(Main.parent,scroller, tr("Clearsigned Signature"), JOptionPane.PLAIN_MESSAGE);116 String[] buttons = {tr("Ok")};117 ExtendedDialog info = new ExtendedDialog(Main.parent, tr("Signature Info"),buttons,false);118 info.setContent(scroller,false);119 info.showDialog();120 }121 122 123 public static void showSignaturesDialog(TrustNode trust) {124 TrustSignatures sigs;125 if ((sigs = trust.getNodeSigs()) == null) {126 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Node."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE);127 } else {128 String nodename = ((Node)trust.getOsmPrimitive()).getDisplayName(DefaultNameFormatter.getInstance());129 showDialog(sigs, tr("Selected node was:\n{0}",nodename),1);130 }131 }132 133 public static void showSignaturesDialog(TrustOsmPrimitive trust, String key) {134 TrustSignatures sigs;135 if ((sigs = trust.getSigsOnKey(key)) == null) {136 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Attribute."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE);137 } else {138 showDialog(sigs, tr("Selected key value pair was:\n{0}={1}",key,trust.getOsmPrimitive().get(key)), 0);139 }140 }141 142 public static void showSignaturesDialog(TrustWay trust, List<Node> nodes) {143 TrustSignatures sigs;144 if ((sigs = trust.getSigsOnSegment(nodes)) == null) {145 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Segment."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE);146 } else {147 showDialog(sigs, tr("Selected WaySegment was:"), 2);148 }149 }150 151 /*152 public static JButton createKeyButton(String label,final long keyID) {153 JButton detailsButton = new JButton(label);154 detailsButton.addActionListener(new ActionListener() {155 156 public void actionPerformed(ActionEvent e)157 {158 showKeySignaturesDialog(keyID);159 }160 });161 return detailsButton;162 }163 164 public static void showKeySignaturesDialog(long keyID) {165 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(keyID);166 JPanel p = new JPanel(new GridBagLayout());167 168 Iterator sigIt = pub.getSignatures();169 while (sigIt.hasNext()) {170 PGPSignature s = (PGPSignature)sigIt.next();171 p.add(createKeyButton(s.getHashedSubPackets().getSignerUserID(),pub.getKeyID()));172 }173 174 String uid = String.valueOf(pub.getKeyID());175 Iterator i = pub.getUserIDs();176 if (i.hasNext())177 uid = (String)i.next();178 179 p.add(createKeyButton(uid,pub.getKeyID()));180 JOptionPane.showMessageDialog(Main.parent,p, tr("Key Signatures"), JOptionPane.PLAIN_MESSAGE);181 }182 183 184 public static String convPGPSignatureToString(PGPSignature s) {185 PGPSignatureSubpacketVector sv = s.getHashedSubPackets();186 if (sv.hasSubpacket(SignatureSubpacketTags.SIGNER_USER_ID))187 return sv.getSignerUserID();188 189 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID());190 if (pub != null){191 Iterator i = pub.getUserIDs();192 if (i.hasNext())193 return (String)i.next();194 }195 return tr("unknown");196 }197 198 public static JTree createSignerTree(Collection<PGPSignature> sigs) {199 DefaultMutableTreeNode root = new DefaultMutableTreeNode();200 for (PGPSignature s : sigs){201 DefaultMutableTreeNode sn = new DefaultMutableTreeNode(s);202 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID());203 Iterator iter = pub.getSignatures();204 while (iter.hasNext()){205 PGPSignature ks = (PGPSignature)iter.next();206 sn.add(new DefaultMutableTreeNode(ks));207 }208 root.add(sn);209 }210 211 212 JTree t = new JTree(new DefaultTreeModel(root));213 t.setRootVisible(false);214 t.setBackground(TrustDialog.BGCOLOR_NO_SIG);215 t.setCellRenderer(new DefaultTreeCellRenderer(){216 217 @Override218 public Component getTreeCellRendererComponent(JTree tree, Object value,219 boolean selected, boolean expanded, boolean leaf, int row,220 boolean hasFocus)221 {222 super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);223 224 DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;225 if (node.isRoot()) return this;226 PGPSignature s = (PGPSignature) node.getUserObject();227 setIcon(ImageProvider.get("dialogs/sign"));228 setText(convPGPSignatureToString(s));229 PGPSignatureSubpacketVector sv = s.getHashedSubPackets();230 setBackgroundNonSelectionColor(TrustDialog.BGCOLOR_NO_SIG);231 if (sv.hasSubpacket(SignatureSubpacketTags.NOTATION_DATA)) {232 for (NotationData nd : sv.getNotationDataOccurences()){233 System.out.println(nd.getNotationName()+"="+nd.getNotationValue());234 if (nd.getNotationName().equals("trustosm@openstreetmap.org")) {235 setBackgroundNonSelectionColor(TrustDialog.BGCOLOR_VALID_SIG);236 setToolTipText(tr("Key certified for OSM-Usage with comment:{0}",nd.getNotationValue()));237 }238 }239 }240 return this;241 }242 243 244 });245 return t;246 }247 248 */42 private static String createLabel(String plain, int type) { 43 if (type == 0) { 44 String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(plain); 45 return tr("Signed key value pair was: {0}={1}", kv[0],kv[1]); 46 } else if (type == 1) { 47 Node node = TrustNode.generateNodeFromSigtext(plain); 48 //return tr("Signed node was: {0}", node.getDisplayName(DefaultNameFormatter.getInstance())); 49 return "ID:"+node.getUniqueId()+" ("+node.getCoor().toString() + ")"; 50 } else if (type == 2) { 51 List<Node> nodes = TrustWay.generateSegmentFromSigtext(plain); 52 return "From:"+nodes.get(0).getUniqueId()+", To:"+nodes.get(nodes.size()-1).getUniqueId(); 53 } 54 return "No known type"; 55 } 56 57 private static void showDialog(TrustSignatures sigs, String label, int type) { 58 JPanel p = new JPanel(new GridBagLayout()); 59 p.add(new JLabel(label),GBC.eol()); 60 61 //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss"); 62 63 for (String plain : sigs.getAllPlainTexts()) { 64 JTextArea sigtext = new JTextArea(sigs.getArmoredFulltextSignatureAll(plain)); 65 sigtext.setEditable(false); 66 JPanel textcontent = new JPanel(); 67 textcontent.add(sigtext); 68 69 p.add(new JCollapsiblePanel(createLabel(plain, type),textcontent),GBC.eol()); 70 71 List<PGPSignature> siglist = sigs.getSignaturesByPlaintext(plain); 72 JPanel signerPanel = new JPanel(new GridBagLayout()); 73 //signerPanel.add(createSignerTree(siglist)); 74 KeyTreeTableModel km = new KeyTreeTableModel(siglist); 75 final JXTreeTable t = new JXTreeTable( km ); 76 //t.setHorizontalScrollEnabled(true); 77 //t.setRootVisible(false); 78 t.addMouseListener(new MouseAdapter() { 79 @Override 80 public void mouseClicked(MouseEvent e) { 81 if (e.getClickCount() == 2) { 82 TreePath selPath = t.getPathForLocation(e.getX(), e.getY()); 83 if (selPath == null) 84 return; 85 SignatureTreeNode sn = (SignatureTreeNode)selPath.getLastPathComponent(); 86 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(sn.getSignature().getKeyID()); 87 TrustGPG.showKeyDetails(pub); 88 } 89 } 90 }); 91 t.setLeafIcon(ImageProvider.get("dialogs/sign")); 92 t.setOpenIcon(ImageProvider.get("dialogs/sign_color")); 93 t.setClosedIcon(ImageProvider.get("dialogs/sign_color")); 94 t.expandAll(); 95 t.packAll(); 96 t.collapseAll(); 97 signerPanel.add(new JScrollPane(t)); 98 99 100 // JTreeTable tt = new JTreeTable(); 101 102 /* for (PGPSignature s : siglist) { 103 signerPanel.add(createKeyButton(tr("Signature created at {0} by User {1}",formatter.format(s.getCreationTime()),s.getHashedSubPackets().getSignerUserID()),s.getKeyID()),GBC.eol()); 104 //signerPanel.add(new JLabel(tr("Signature created at {0} by User {1}",formatter.format(s.getCreationTime()),s.getHashedSubPackets().getSignerUserID())),GBC.eol()); 105 }*/ 106 107 p.add(new JCollapsiblePanel(tr("{0} Signatures found.", siglist.size()),signerPanel),GBC.eol().insets(20,0,0,0)); 108 } 109 p.add(Box.createVerticalGlue(), GBC.eol().fill(GBC.BOTH)); 110 JScrollPane scroller = new JScrollPane(p); 111 //JPanel content = new JPanel(); 112 scroller.setPreferredSize(new Dimension(700,500)); 113 //content.add(scroller); 114 //JOptionPane.showMessageDialog(Main.parent,scroller, tr("Clearsigned Signature"), JOptionPane.PLAIN_MESSAGE); 115 String[] buttons = {tr("Ok")}; 116 ExtendedDialog info = new ExtendedDialog(Main.parent, tr("Signature Info"),buttons,false); 117 info.setContent(scroller,false); 118 info.showDialog(); 119 } 120 121 122 public static void showSignaturesDialog(TrustNode trust) { 123 TrustSignatures sigs; 124 if ((sigs = trust.getNodeSigs()) == null) { 125 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Node."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE); 126 } else { 127 String nodename = ((Node)trust.getOsmPrimitive()).getDisplayName(DefaultNameFormatter.getInstance()); 128 showDialog(sigs, tr("Selected node was:\n{0}",nodename),1); 129 } 130 } 131 132 public static void showSignaturesDialog(TrustOsmPrimitive trust, String key) { 133 TrustSignatures sigs; 134 if ((sigs = trust.getSigsOnKey(key)) == null) { 135 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Attribute."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE); 136 } else { 137 showDialog(sigs, tr("Selected key value pair was:\n{0}={1}",key,trust.getOsmPrimitive().get(key)), 0); 138 } 139 } 140 141 public static void showSignaturesDialog(TrustWay trust, List<Node> nodes) { 142 TrustSignatures sigs; 143 if ((sigs = trust.getSigsOnSegment(nodes)) == null) { 144 JOptionPane.showMessageDialog(null,tr("Sorry, there are no Signatures for the selected Segment."), tr("No Signature found"), JOptionPane.WARNING_MESSAGE); 145 } else { 146 showDialog(sigs, tr("Selected WaySegment was:"), 2); 147 } 148 } 149 150 /* 151 public static JButton createKeyButton(String label,final long keyID) { 152 JButton detailsButton = new JButton(label); 153 detailsButton.addActionListener(new ActionListener() { 154 155 public void actionPerformed(ActionEvent e) 156 { 157 showKeySignaturesDialog(keyID); 158 } 159 }); 160 return detailsButton; 161 } 162 163 public static void showKeySignaturesDialog(long keyID) { 164 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(keyID); 165 JPanel p = new JPanel(new GridBagLayout()); 166 167 Iterator sigIt = pub.getSignatures(); 168 while (sigIt.hasNext()) { 169 PGPSignature s = (PGPSignature)sigIt.next(); 170 p.add(createKeyButton(s.getHashedSubPackets().getSignerUserID(),pub.getKeyID())); 171 } 172 173 String uid = String.valueOf(pub.getKeyID()); 174 Iterator i = pub.getUserIDs(); 175 if (i.hasNext()) 176 uid = (String)i.next(); 177 178 p.add(createKeyButton(uid,pub.getKeyID())); 179 JOptionPane.showMessageDialog(Main.parent,p, tr("Key Signatures"), JOptionPane.PLAIN_MESSAGE); 180 } 181 182 183 public static String convPGPSignatureToString(PGPSignature s) { 184 PGPSignatureSubpacketVector sv = s.getHashedSubPackets(); 185 if (sv.hasSubpacket(SignatureSubpacketTags.SIGNER_USER_ID)) 186 return sv.getSignerUserID(); 187 188 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID()); 189 if (pub != null){ 190 Iterator i = pub.getUserIDs(); 191 if (i.hasNext()) 192 return (String)i.next(); 193 } 194 return tr("unknown"); 195 } 196 197 public static JTree createSignerTree(Collection<PGPSignature> sigs) { 198 DefaultMutableTreeNode root = new DefaultMutableTreeNode(); 199 for (PGPSignature s : sigs){ 200 DefaultMutableTreeNode sn = new DefaultMutableTreeNode(s); 201 PGPPublicKey pub = TrustOSMplugin.gpg.getPublicKeyFromRing(s.getKeyID()); 202 Iterator iter = pub.getSignatures(); 203 while (iter.hasNext()){ 204 PGPSignature ks = (PGPSignature)iter.next(); 205 sn.add(new DefaultMutableTreeNode(ks)); 206 } 207 root.add(sn); 208 } 209 210 211 JTree t = new JTree(new DefaultTreeModel(root)); 212 t.setRootVisible(false); 213 t.setBackground(TrustDialog.BGCOLOR_NO_SIG); 214 t.setCellRenderer(new DefaultTreeCellRenderer(){ 215 216 @Override 217 public Component getTreeCellRendererComponent(JTree tree, Object value, 218 boolean selected, boolean expanded, boolean leaf, int row, 219 boolean hasFocus) 220 { 221 super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); 222 223 DefaultMutableTreeNode node = (DefaultMutableTreeNode)value; 224 if (node.isRoot()) return this; 225 PGPSignature s = (PGPSignature) node.getUserObject(); 226 setIcon(ImageProvider.get("dialogs/sign")); 227 setText(convPGPSignatureToString(s)); 228 PGPSignatureSubpacketVector sv = s.getHashedSubPackets(); 229 setBackgroundNonSelectionColor(TrustDialog.BGCOLOR_NO_SIG); 230 if (sv.hasSubpacket(SignatureSubpacketTags.NOTATION_DATA)) { 231 for (NotationData nd : sv.getNotationDataOccurences()){ 232 System.out.println(nd.getNotationName()+"="+nd.getNotationValue()); 233 if (nd.getNotationName().equals("trustosm@openstreetmap.org")) { 234 setBackgroundNonSelectionColor(TrustDialog.BGCOLOR_VALID_SIG); 235 setToolTipText(tr("Key certified for OSM-Usage with comment:{0}",nd.getNotationValue())); 236 } 237 } 238 } 239 return this; 240 } 241 242 243 }); 244 return t; 245 } 246 247 */ 249 248 250 249 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/io/SigExporter.java
r25269 r30724 18 18 public class SigExporter extends FileExporter { 19 19 20 public SigExporter(ExtensionFileFilter filter) {21 super(filter);22 // TODO Auto-generated constructor stub23 }20 public SigExporter(ExtensionFileFilter filter) { 21 super(filter); 22 // TODO Auto-generated constructor stub 23 } 24 24 25 public SigExporter() {26 super(new ExtensionFileFilter("txml,xml", "txml", tr("Signature Files") + " (*.txml *.xml)"));27 }25 public SigExporter() { 26 super(new ExtensionFileFilter("txml,xml", "txml", tr("Signature Files") + " (*.txml *.xml)")); 27 } 28 28 29 @Override30 public void exportData(File file, Layer layer) throws IOException {31 CheckParameterUtil.ensureParameterNotNull(file, "file");29 @Override 30 public void exportData(File file, Layer layer) throws IOException { 31 CheckParameterUtil.ensureParameterNotNull(file, "file"); 32 32 33 String fn = file.getPath(); 34 if (fn.indexOf('.') == -1) { 35 fn += ".tosm"; 36 file = new File(fn); 37 } 38 try { 39 FileOutputStream fo = new FileOutputStream(file); 40 new SigWriter(fo).write(TrustOSMplugin.signedItems.values()); 41 fo.flush(); 42 fo.close(); 43 } catch (IOException x) { 44 x.printStackTrace(); 45 JOptionPane.showMessageDialog(Main.parent, tr("Error while exporting {0}:\n{1}", fn, x.getMessage()), 46 tr("Error"), JOptionPane.ERROR_MESSAGE); 47 } 48 } 33 String fn = file.getPath(); 34 if (fn.indexOf('.') == -1) { 35 fn += ".tosm"; 36 file = new File(fn); 37 } 38 try (FileOutputStream fo = new FileOutputStream(file)) { 39 new SigWriter(fo).write(TrustOSMplugin.signedItems.values()); 40 fo.flush(); 41 } catch (IOException x) { 42 x.printStackTrace(); 43 JOptionPane.showMessageDialog(Main.parent, tr("Error while exporting {0}:\n{1}", fn, x.getMessage()), 44 tr("Error"), JOptionPane.ERROR_MESSAGE); 45 } 46 } 49 47 50 48 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/io/SigImporter.java
r25785 r30724 24 24 public class SigImporter extends FileImporter { 25 25 26 public SigImporter() {27 super(new ExtensionFileFilter("txml,xml", "txml", tr("OSM Signature Files") + " (*.txml *.xml)"));28 }26 public SigImporter() { 27 super(new ExtensionFileFilter("txml,xml", "txml", tr("OSM Signature Files") + " (*.txml *.xml)")); 28 } 29 29 30 public SigImporter(ExtensionFileFilter filter) {31 super(filter);32 }30 public SigImporter(ExtensionFileFilter filter) { 31 super(filter); 32 } 33 33 34 @Override public void importData(File file, ProgressMonitor progressMonitor) throws IOException, IllegalDataException {35 try {36 FileInputStream in = new FileInputStream(file);37 importData(in, file);38 } catch (FileNotFoundException e) {39 e.printStackTrace();40 throw new IOException(tr("File ''{0}'' does not exist.", file.getName()));41 }42 }34 @Override public void importData(File file, ProgressMonitor progressMonitor) throws IOException, IllegalDataException { 35 try { 36 FileInputStream in = new FileInputStream(file); 37 importData(in, file); 38 } catch (FileNotFoundException e) { 39 e.printStackTrace(); 40 throw new IOException(tr("File ''{0}'' does not exist.", file.getName())); 41 } 42 } 43 43 44 protected void importData(InputStream in, File associatedFile) throws IllegalDataException {45 if (!Main.main.hasEditLayer()) {46 DataSet dataSet = new DataSet();47 final OsmDataLayer layer = new OsmDataLayer(dataSet, associatedFile.getName(), associatedFile);48 Main.main.addLayer(layer);49 }50 //Set<OsmPrimitive> missingData = new HashSet<OsmPrimitive>();51 Map<String,TrustOsmPrimitive> trustitems = SigReader.parseSignatureXML(in, NullProgressMonitor.INSTANCE);52 System.out.println(trustitems.size());53 /*54 int missingCount = missingData.size();55 int itemCount = trustitems.size();56 if (missingCount == 0) {57 JOptionPane.showMessageDialog(Main.parent, tr("{0} Signatures loaded. All referenced OSM objects found.",itemCount));58 } else {59 int n = JOptionPane.showOptionDialog(Main.parent, tr("{0} of {1} OSM objects are referenced but not there.\nDo you want to load them from OSM-Server?",missingCount,itemCount), tr("Load objects from server"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);44 protected void importData(InputStream in, File associatedFile) throws IllegalDataException { 45 if (!Main.main.hasEditLayer()) { 46 DataSet dataSet = new DataSet(); 47 final OsmDataLayer layer = new OsmDataLayer(dataSet, associatedFile.getName(), associatedFile); 48 Main.main.addLayer(layer); 49 } 50 // Set<OsmPrimitive> missingData = new HashSet<OsmPrimitive>(); 51 Map<String,TrustOsmPrimitive> trustitems = SigReader.parseSignatureXML(in, NullProgressMonitor.INSTANCE); 52 System.out.println(trustitems.size()); 53 /* 54 int missingCount = missingData.size(); 55 int itemCount = trustitems.size(); 56 if (missingCount == 0) { 57 JOptionPane.showMessageDialog(Main.parent, tr("{0} Signatures loaded. All referenced OSM objects found.",itemCount)); 58 } else { 59 int n = JOptionPane.showOptionDialog(Main.parent, tr("{0} of {1} OSM objects are referenced but not there.\nDo you want to load them from OSM-Server?",missingCount,itemCount), tr("Load objects from server"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 60 60 61 if (n == JOptionPane.YES_OPTION) {62 Main.worker.submit(new DownloadSignedOsmDataTask(missingData, Main.main.getEditLayer()));63 }64 }65 */66 TrustOSMplugin.signedItems.putAll(trustitems);67 new GetMissingDataAction().downloadMissing();68 //TrustOSMplugin.signedItems.putAll(TrustStoreHandler.loadSigsFromFile(in));61 if (n == JOptionPane.YES_OPTION) { 62 Main.worker.submit(new DownloadSignedOsmDataTask(missingData, Main.main.getEditLayer())); 63 } 64 } 65 */ 66 TrustOSMplugin.signedItems.putAll(trustitems); 67 new GetMissingDataAction().downloadMissing(); 68 //TrustOSMplugin.signedItems.putAll(TrustStoreHandler.loadSigsFromFile(in)); 69 69 70 }70 } 71 71 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/io/SigReader.java
r25785 r30724 30 30 import org.openstreetmap.josm.gui.progress.ProgressMonitor; 31 31 import org.openstreetmap.josm.io.IllegalDataException; 32 import org.openstreetmap.josm.io.OsmDataParsingException;33 32 import org.openstreetmap.josm.io.UTFInputStreamReader; 34 33 import org.openstreetmap.josm.plugins.trustosm.data.TrustNode; … … 38 37 import org.openstreetmap.josm.plugins.trustosm.data.TrustWay; 39 38 import org.openstreetmap.josm.tools.CheckParameterUtil; 39 import org.openstreetmap.josm.tools.XmlParsingException; 40 40 import org.xml.sax.Attributes; 41 41 import org.xml.sax.InputSource; … … 47 47 public class SigReader { 48 48 49 private final Map<String,TrustOsmPrimitive> trustitems = new HashMap<String,TrustOsmPrimitive>();50 private final Set<OsmPrimitive> missingData = new HashSet<OsmPrimitive>();51 52 public Map<String,TrustOsmPrimitive> getTrustItems() {53 return trustitems;54 }55 56 public Set<OsmPrimitive> getMissingData() {57 return missingData;58 }59 60 private class Parser extends DefaultHandler {61 private Locator locator;62 63 @Override64 public void setDocumentLocator(Locator locator) {65 this.locator = locator;66 }67 68 protected void throwException(String msg) throwsOsmDataParsingException{69 throw newOsmDataParsingException(msg).rememberLocation(locator);70 }71 72 /**73 * The current TrustOSMItem to be read.74 */75 private TrustOsmPrimitive trust;76 77 78 /**79 * The current Signatures.80 */81 private TrustSignatures tsigs;82 83 84 private StringBuffer tmpbuf = new StringBuffer();85 86 87 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {88 89 try {90 if (qName.equals("trustnode") || qName.equals("trustway") || qName.equals("trustrelation")) {91 if (atts == null) {92 throwException(tr("Missing mandatory attribute ''{0}'' of XML element {1}.", "osmid", qName));93 }94 95 String osmid = atts.getValue("osmid");96 if (osmid == null){97 throwException(tr("Missing mandatory attribute ''{0}''.", "osmid"));98 } else if (!osmid.matches("\\d+")) {99 throwException(tr("Only digits allowed in osmid: ''{0}''.", osmid));100 }101 long uid = Long.parseLong(osmid);102 103 OsmPrimitiveType t = OsmPrimitiveType.NODE;104 if (qName.equals("trustway")) t = OsmPrimitiveType.WAY;105 else if (qName.equals("trustrelation")) t = OsmPrimitiveType.RELATION;106 107 // search corresponding OsmPrimitive108 OsmPrimitive osm = Main.main.getCurrentDataSet().getPrimitiveById(uid, t);109 if (osm == null) {110 switch (t) {111 case NODE: osm = new Node(uid); break;112 case WAY: osm = new Way(uid); break;113 case RELATION: osm = new Relation(uid); break;114 }115 missingData.add(osm);116 }117 trust = TrustOsmPrimitive.createTrustOsmPrimitive(osm);118 119 } else if (qName.equals("key") || qName.equals("node") || qName.equals("segment") || qName.equals("member")) {120 tsigs = new TrustSignatures();121 } else if (qName.equals("openpgp")) {122 tmpbuf = new StringBuffer();123 }124 } catch (Exception e) {125 throw new SAXParseException(e.getMessage(), locator, e);126 }127 }128 129 @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException {130 if (qName.equals("trustnode") || qName.equals("trustway") || qName.equals("trustrelation")) {131 trustitems.put(TrustOsmPrimitive.createUniqueObjectIdentifier(trust.getOsmPrimitive()), trust);132 } else if (qName.equals("openpgp")) {133 // System.out.println(tmpbuf.toString());134 try {135 parseOpenPGP(tmpbuf.toString());136 } catch (IOException e) {137 throw newOsmDataParsingException(tr("Could not parse OpenPGP message."),e).rememberLocation(locator);138 }139 } else if (qName.equals("key")) {140 String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(tsigs.getOnePlainText());141 trust.setTagRatings(kv[0], tsigs);142 } else if (qName.equals("node")) {143 ((TrustNode)trust).setNodeRatings(tsigs);144 } else if (qName.equals("segment")) {145 List<Node> nodes = TrustWay.generateSegmentFromSigtext(tsigs.getOnePlainText());146 ((TrustWay)trust).setSegmentRatings(nodes,tsigs);147 } else if (qName.equals("member")) {148 RelationMember member = TrustRelation.generateRelationMemberFromSigtext(tsigs.getOnePlainText());149 ((TrustRelation)trust).setMemberRating(TrustOsmPrimitive.createUniqueObjectIdentifier(member.getMember()), tsigs);150 }151 }152 153 @Override public void characters(char[] ch, int start, int length) {154 tmpbuf.append(ch, start, length);155 }156 157 public void parseOpenPGP(String clearsigned) throws IOException {158 159 // handle different newline characters and match them all to \n160 //clearsigned = clearsigned.replace('\r', '\n').replaceAll("\n\n", "\n");161 162 String plain = "";163 164 ArmoredInputStream aIn = new ArmoredInputStream(new ByteArrayInputStream(clearsigned.getBytes(Charset.forName("UTF-8"))));165 PGPObjectFactory pgpFact = new PGPObjectFactory(aIn);166 // read plain text167 ByteArrayOutputStream bout = new ByteArrayOutputStream();168 if (aIn.isClearText()) {169 int ch = aIn.read();170 do {171 bout.write(ch);172 ch = aIn.read();173 } while (aIn.isClearText());174 }175 plain = bout.toString();176 177 // remove the last \n because it is not part of the plaintext178 plain = plain.substring(0, plain.length()-1);179 180 PGPSignatureList siglist = (PGPSignatureList)pgpFact.nextObject();181 for (int i=0; i<siglist.size();i++) {182 tsigs.addSignature(siglist.get(i), plain);183 }184 185 186 }187 188 189 }190 191 /**192 * Parse the given input source and return the TrustosmItems.193 *194 * @param source the source input stream. Must not be null.195 * @param progressMonitor the progress monitor. If null, {@see NullProgressMonitor#INSTANCE} is assumed196 *197 * @return a map of the parsed OSM Signatures (TrustOSMItem) with their related OSM-ID as key198 * @throws IllegalDataException thrown if the an error was found while parsing the data from the source199 * @throws IllegalArgumentException thrown if source is null200 */201 public static Map<String,TrustOsmPrimitive> parseSignatureXML(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException {202 if (progressMonitor == null) {203 progressMonitor = NullProgressMonitor.INSTANCE;204 }205 CheckParameterUtil.ensureParameterNotNull(source, "source");206 SigReader reader = new SigReader();207 try {208 progressMonitor.beginTask(tr("Prepare stuff...", 2));209 progressMonitor.indeterminateSubTask(tr("Parsing Signature data..."));210 211 InputSource inputSource = new InputSource(UTFInputStreamReader.create(source, "UTF-8"));212 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, reader.new Parser());213 //if (missingData != null)214 //missingData.addAll(reader.getMissingData());215 progressMonitor.worked(1);216 217 return reader.getTrustItems();218 } catch(ParserConfigurationException e) {219 throw new IllegalDataException(e.getMessage(), e);220 } catch (SAXParseException e) {221 throw new IllegalDataException(tr("Line {0} column {1}: ", e.getLineNumber(), e.getColumnNumber()) + e.getMessage(), e);222 } catch(SAXException e) {223 throw new IllegalDataException(e.getMessage(), e);224 } catch(Exception e) {225 throw new IllegalDataException(e);226 } finally {227 progressMonitor.finishTask();228 }229 }49 private final Map<String,TrustOsmPrimitive> trustitems = new HashMap<>(); 50 private final Set<OsmPrimitive> missingData = new HashSet<>(); 51 52 public Map<String,TrustOsmPrimitive> getTrustItems() { 53 return trustitems; 54 } 55 56 public Set<OsmPrimitive> getMissingData() { 57 return missingData; 58 } 59 60 private class Parser extends DefaultHandler { 61 private Locator locator; 62 63 @Override 64 public void setDocumentLocator(Locator locator) { 65 this.locator = locator; 66 } 67 68 protected void throwException(String msg) throws XmlParsingException { 69 throw new XmlParsingException(msg).rememberLocation(locator); 70 } 71 72 /** 73 * The current TrustOSMItem to be read. 74 */ 75 private TrustOsmPrimitive trust; 76 77 78 /** 79 * The current Signatures. 80 */ 81 private TrustSignatures tsigs; 82 83 84 private StringBuffer tmpbuf = new StringBuffer(); 85 86 87 @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException { 88 89 try { 90 if (qName.equals("trustnode") || qName.equals("trustway") || qName.equals("trustrelation")) { 91 if (atts == null) { 92 throwException(tr("Missing mandatory attribute ''{0}'' of XML element {1}.", "osmid", qName)); 93 } 94 95 String osmid = atts.getValue("osmid"); 96 if (osmid == null){ 97 throwException(tr("Missing mandatory attribute ''{0}''.", "osmid")); 98 } else if (!osmid.matches("\\d+")) { 99 throwException(tr("Only digits allowed in osmid: ''{0}''.", osmid)); 100 } 101 long uid = Long.parseLong(osmid); 102 103 OsmPrimitiveType t = OsmPrimitiveType.NODE; 104 if (qName.equals("trustway")) t = OsmPrimitiveType.WAY; 105 else if (qName.equals("trustrelation")) t = OsmPrimitiveType.RELATION; 106 107 // search corresponding OsmPrimitive 108 OsmPrimitive osm = Main.main.getCurrentDataSet().getPrimitiveById(uid, t); 109 if (osm == null) { 110 switch (t) { 111 case NODE: osm = new Node(uid); break; 112 case WAY: osm = new Way(uid); break; 113 case RELATION: osm = new Relation(uid); break; 114 } 115 missingData.add(osm); 116 } 117 trust = TrustOsmPrimitive.createTrustOsmPrimitive(osm); 118 119 } else if (qName.equals("key") || qName.equals("node") || qName.equals("segment") || qName.equals("member")) { 120 tsigs = new TrustSignatures(); 121 } else if (qName.equals("openpgp")) { 122 tmpbuf = new StringBuffer(); 123 } 124 } catch (Exception e) { 125 throw new SAXParseException(e.getMessage(), locator, e); 126 } 127 } 128 129 @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { 130 if (qName.equals("trustnode") || qName.equals("trustway") || qName.equals("trustrelation")) { 131 trustitems.put(TrustOsmPrimitive.createUniqueObjectIdentifier(trust.getOsmPrimitive()), trust); 132 } else if (qName.equals("openpgp")) { 133 // System.out.println(tmpbuf.toString()); 134 try { 135 parseOpenPGP(tmpbuf.toString()); 136 } catch (IOException e) { 137 throw new XmlParsingException(tr("Could not parse OpenPGP message."),e).rememberLocation(locator); 138 } 139 } else if (qName.equals("key")) { 140 String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(tsigs.getOnePlainText()); 141 trust.setTagRatings(kv[0], tsigs); 142 } else if (qName.equals("node")) { 143 ((TrustNode)trust).setNodeRatings(tsigs); 144 } else if (qName.equals("segment")) { 145 List<Node> nodes = TrustWay.generateSegmentFromSigtext(tsigs.getOnePlainText()); 146 ((TrustWay)trust).setSegmentRatings(nodes,tsigs); 147 } else if (qName.equals("member")) { 148 RelationMember member = TrustRelation.generateRelationMemberFromSigtext(tsigs.getOnePlainText()); 149 ((TrustRelation)trust).setMemberRating(TrustOsmPrimitive.createUniqueObjectIdentifier(member.getMember()), tsigs); 150 } 151 } 152 153 @Override public void characters(char[] ch, int start, int length) { 154 tmpbuf.append(ch, start, length); 155 } 156 157 public void parseOpenPGP(String clearsigned) throws IOException { 158 159 // handle different newline characters and match them all to \n 160 //clearsigned = clearsigned.replace('\r', '\n').replaceAll("\n\n", "\n"); 161 162 String plain = ""; 163 164 ArmoredInputStream aIn = new ArmoredInputStream(new ByteArrayInputStream(clearsigned.getBytes(Charset.forName("UTF-8")))); 165 PGPObjectFactory pgpFact = new PGPObjectFactory(aIn); 166 // read plain text 167 ByteArrayOutputStream bout = new ByteArrayOutputStream(); 168 if (aIn.isClearText()) { 169 int ch = aIn.read(); 170 do { 171 bout.write(ch); 172 ch = aIn.read(); 173 } while (aIn.isClearText()); 174 } 175 plain = bout.toString(); 176 177 // remove the last \n because it is not part of the plaintext 178 plain = plain.substring(0, plain.length()-1); 179 180 PGPSignatureList siglist = (PGPSignatureList)pgpFact.nextObject(); 181 for (int i=0; i<siglist.size();i++) { 182 tsigs.addSignature(siglist.get(i), plain); 183 } 184 185 186 } 187 188 189 } 190 191 /** 192 * Parse the given input source and return the TrustosmItems. 193 * 194 * @param source the source input stream. Must not be null. 195 * @param progressMonitor the progress monitor. If null, {@see NullProgressMonitor#INSTANCE} is assumed 196 * 197 * @return a map of the parsed OSM Signatures (TrustOSMItem) with their related OSM-ID as key 198 * @throws IllegalDataException thrown if the an error was found while parsing the data from the source 199 * @throws IllegalArgumentException thrown if source is null 200 */ 201 public static Map<String,TrustOsmPrimitive> parseSignatureXML(InputStream source, ProgressMonitor progressMonitor) throws IllegalDataException { 202 if (progressMonitor == null) { 203 progressMonitor = NullProgressMonitor.INSTANCE; 204 } 205 CheckParameterUtil.ensureParameterNotNull(source, "source"); 206 SigReader reader = new SigReader(); 207 try { 208 progressMonitor.beginTask(tr("Prepare stuff...", 2)); 209 progressMonitor.indeterminateSubTask(tr("Parsing Signature data...")); 210 211 InputSource inputSource = new InputSource(UTFInputStreamReader.create(source, "UTF-8")); 212 SAXParserFactory.newInstance().newSAXParser().parse(inputSource, reader.new Parser()); 213 // if (missingData != null) 214 // missingData.addAll(reader.getMissingData()); 215 progressMonitor.worked(1); 216 217 return reader.getTrustItems(); 218 } catch(ParserConfigurationException e) { 219 throw new IllegalDataException(e.getMessage(), e); 220 } catch (SAXParseException e) { 221 throw new IllegalDataException(tr("Line {0} column {1}: ", e.getLineNumber(), e.getColumnNumber()) + e.getMessage(), e); 222 } catch(SAXException e) { 223 throw new IllegalDataException(e.getMessage(), e); 224 } catch(Exception e) { 225 throw new IllegalDataException(e); 226 } finally { 227 progressMonitor.finishTask(); 228 } 229 } 230 230 231 231 -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/io/SigWriter.java
r25269 r30724 22 22 public class SigWriter extends XmlWriter { 23 23 24 private String indent = "";25 26 public SigWriter(PrintWriter out) {27 super(out);28 }29 30 public SigWriter(OutputStream out) throws UnsupportedEncodingException {31 super(new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));32 }33 34 public void write(Collection<TrustOsmPrimitive> items) {35 writeHeader();36 indent = " ";37 writeItems(items);38 writeFooter();39 out.flush();40 }41 42 private void writeDTD() {43 out.println("<!DOCTYPE trustXML [");44 out.println(" <!ELEMENT trustXML (trustnode|trustway|trustrelation)*>");45 out.println(" <!ATTLIST trustXML version CDATA #IMPLIED creator CDATA #IMPLIED >");46 out.println(" <!ELEMENT trustnode (tags?,node?)>");47 out.println(" <!ELEMENT trustway (tags?,segmentlist?)>");48 out.println(" <!ELEMENT trustrelation (tags?,memberlist?)>");49 out.println(" <!ATTLIST trustnode osmid CDATA #IMPLIED >");50 out.println(" <!ATTLIST trustway osmid CDATA #IMPLIED >");51 out.println(" <!ATTLIST trustrelation osmid CDATA #IMPLIED >");52 out.println(" <!ELEMENT tags (key)+>");53 out.println(" <!ELEMENT key (openpgp)+>");54 out.println(" <!ATTLIST key k CDATA #IMPLIED >");55 out.println(" <!ELEMENT node (openpgp)>");56 //out.println(" <!ATTLIST node id CDATA #REQUIRED >");57 out.println(" <!ELEMENT segmentlist (segment)*>");58 out.println(" <!ELEMENT segment (openpgp)+>");59 out.println(" <!ELEMENT memberlist (member)*>");60 out.println(" <!ELEMENT member (openpgp)+>");61 out.println(" <!ELEMENT openpgp (#PCDATA)*>");62 out.println("]>");63 }64 65 private void writeHeader() {66 out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");67 writeDTD();68 out.println("<trustXML version=\"0.1\" creator=\"JOSM Signature export\">");69 }70 71 private void writeFooter() {72 out.println("</trustXML>");73 }74 75 private void writeSigs(TrustSignatures tsigs) {76 for (String plain : tsigs.getAllPlainTexts()) {77 simpleTag("openpgp",tsigs.getArmoredFulltextSignatureAll(plain));78 }79 80 }81 82 private void writeTags(TrustOsmPrimitive trust) {83 Map<String, TrustSignatures> tagsigs = trust.getTagSigs();84 Set<String> signedKeys = tagsigs.keySet();85 if (signedKeys.isEmpty()) return;86 openln("tags");87 for (String key : signedKeys) {88 openAtt("key","k=\""+key+"\"");89 90 writeSigs(tagsigs.get(key));91 92 closeln("key");93 }94 closeln("tags");95 }96 97 private void writeNode(TrustNode tn) {98 TrustSignatures tsigs = tn.getNodeSigs();99 if (tsigs == null) return;100 openln("node");101 writeSigs(tsigs);102 closeln("node");103 }104 105 private void writeSegments(TrustWay tw) {106 Map<List<Node>, TrustSignatures> segmentSig = tw.getSegmentSigs();107 Set<List<Node>> signedSegments = segmentSig.keySet();108 if (signedSegments.isEmpty()) return;109 openln("segmentlist");110 for (List<Node> segment : signedSegments) {111 openln("segment");112 writeSigs(segmentSig.get(segment));113 closeln("segment");114 }115 closeln("segmentlist");116 }117 118 private void writeMembers(TrustRelation tr) {119 Map<String, TrustSignatures> memberSig = tr.getMemberSigs();120 Set<String> signedMembers = memberSig.keySet();121 if (signedMembers.isEmpty()) return;122 openln("memberlist");123 for (String member : signedMembers) {124 openln("member");125 writeSigs(memberSig.get(member));126 closeln("member");127 }128 closeln("memberlist");129 }130 131 private void writeItems(Collection<TrustOsmPrimitive> items) {132 133 for (TrustOsmPrimitive trust : items){134 OsmPrimitive osm = trust.getOsmPrimitive();135 if (trust instanceof TrustNode) {136 TrustNode tn = (TrustNode) trust;137 openAtt("trustnode", "osmid=\""+String.valueOf(osm.getUniqueId())+"\"");138 writeTags(tn);139 writeNode(tn);140 closeln("trustnode");141 } else if (trust instanceof TrustWay) {142 TrustWay tw = (TrustWay) trust;143 openAtt("trustway", "osmid=\""+String.valueOf(osm.getUniqueId())+"\"");144 writeTags(tw);145 writeSegments(tw);146 closeln("trustway");147 } else if (trust instanceof TrustRelation) {148 TrustRelation tr = (TrustRelation) trust;149 openAtt("trustrelation", "osmid=\""+String.valueOf(osm.getUniqueId())+"\"");150 writeTags(tr);151 writeMembers(tr);152 closeln("trustrelation");153 }154 155 //openAtt("trustitem", "osmid=\""+String.valueOf(osm.getUniqueId())+"\" type=\""+osm.getType().getAPIName()+"\"");156 157 }158 }159 160 private void openln(String tag) {161 open(tag);162 out.println();163 }164 165 private void open(String tag) {166 out.print(indent + "<" + tag + ">");167 indent += " ";168 }169 170 private void openAtt(String tag, String attributes) {171 out.println(indent + "<" + tag + " " + attributes + ">");172 indent += " ";173 }174 175 private void inline(String tag, String attributes) {176 out.println(indent + "<" + tag + " " + attributes + " />");177 } 178 179 private void close(String tag) {180 indent = indent.substring(2);181 out.print(indent + "</" + tag + ">");182 }183 184 private void closeln(String tag) {185 close(tag);186 out.println();187 }188 189 /**190 * if content not null, open tag, write encoded content, and close tag191 * else do nothing.192 */193 private void simpleTag(String tag, String content) {194 if (content != null && content.length() > 0) {195 open(tag);196 out.print(encode(content));197 //out.print(content);198 out.println("</" + tag + ">");199 indent = indent.substring(2);200 }201 }24 private String indent = ""; 25 26 public SigWriter(PrintWriter out) { 27 super(out); 28 } 29 30 public SigWriter(OutputStream out) throws UnsupportedEncodingException { 31 super(new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8")))); 32 } 33 34 public void write(Collection<TrustOsmPrimitive> items) { 35 writeHeader(); 36 indent = " "; 37 writeItems(items); 38 writeFooter(); 39 out.flush(); 40 } 41 42 private void writeDTD() { 43 out.println("<!DOCTYPE trustXML ["); 44 out.println(" <!ELEMENT trustXML (trustnode|trustway|trustrelation)*>"); 45 out.println(" <!ATTLIST trustXML version CDATA #IMPLIED creator CDATA #IMPLIED >"); 46 out.println(" <!ELEMENT trustnode (tags?,node?)>"); 47 out.println(" <!ELEMENT trustway (tags?,segmentlist?)>"); 48 out.println(" <!ELEMENT trustrelation (tags?,memberlist?)>"); 49 out.println(" <!ATTLIST trustnode osmid CDATA #IMPLIED >"); 50 out.println(" <!ATTLIST trustway osmid CDATA #IMPLIED >"); 51 out.println(" <!ATTLIST trustrelation osmid CDATA #IMPLIED >"); 52 out.println(" <!ELEMENT tags (key)+>"); 53 out.println(" <!ELEMENT key (openpgp)+>"); 54 out.println(" <!ATTLIST key k CDATA #IMPLIED >"); 55 out.println(" <!ELEMENT node (openpgp)>"); 56 // out.println(" <!ATTLIST node id CDATA #REQUIRED >"); 57 out.println(" <!ELEMENT segmentlist (segment)*>"); 58 out.println(" <!ELEMENT segment (openpgp)+>"); 59 out.println(" <!ELEMENT memberlist (member)*>"); 60 out.println(" <!ELEMENT member (openpgp)+>"); 61 out.println(" <!ELEMENT openpgp (#PCDATA)*>"); 62 out.println("]>"); 63 } 64 65 private void writeHeader() { 66 out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); 67 writeDTD(); 68 out.println("<trustXML version=\"0.1\" creator=\"JOSM Signature export\">"); 69 } 70 71 private void writeFooter() { 72 out.println("</trustXML>"); 73 } 74 75 private void writeSigs(TrustSignatures tsigs) { 76 for (String plain : tsigs.getAllPlainTexts()) { 77 simpleTag("openpgp",tsigs.getArmoredFulltextSignatureAll(plain)); 78 } 79 80 } 81 82 private void writeTags(TrustOsmPrimitive trust) { 83 Map<String, TrustSignatures> tagsigs = trust.getTagSigs(); 84 Set<String> signedKeys = tagsigs.keySet(); 85 if (signedKeys.isEmpty()) return; 86 openln("tags"); 87 for (String key : signedKeys) { 88 openAtt("key","k=\""+key+"\""); 89 90 writeSigs(tagsigs.get(key)); 91 92 closeln("key"); 93 } 94 closeln("tags"); 95 } 96 97 private void writeNode(TrustNode tn) { 98 TrustSignatures tsigs = tn.getNodeSigs(); 99 if (tsigs == null) return; 100 openln("node"); 101 writeSigs(tsigs); 102 closeln("node"); 103 } 104 105 private void writeSegments(TrustWay tw) { 106 Map<List<Node>, TrustSignatures> segmentSig = tw.getSegmentSigs(); 107 Set<List<Node>> signedSegments = segmentSig.keySet(); 108 if (signedSegments.isEmpty()) return; 109 openln("segmentlist"); 110 for (List<Node> segment : signedSegments) { 111 openln("segment"); 112 writeSigs(segmentSig.get(segment)); 113 closeln("segment"); 114 } 115 closeln("segmentlist"); 116 } 117 118 private void writeMembers(TrustRelation tr) { 119 Map<String, TrustSignatures> memberSig = tr.getMemberSigs(); 120 Set<String> signedMembers = memberSig.keySet(); 121 if (signedMembers.isEmpty()) return; 122 openln("memberlist"); 123 for (String member : signedMembers) { 124 openln("member"); 125 writeSigs(memberSig.get(member)); 126 closeln("member"); 127 } 128 closeln("memberlist"); 129 } 130 131 private void writeItems(Collection<TrustOsmPrimitive> items) { 132 133 for (TrustOsmPrimitive trust : items){ 134 OsmPrimitive osm = trust.getOsmPrimitive(); 135 if (trust instanceof TrustNode) { 136 TrustNode tn = (TrustNode) trust; 137 openAtt("trustnode", "osmid=\""+String.valueOf(osm.getUniqueId())+"\""); 138 writeTags(tn); 139 writeNode(tn); 140 closeln("trustnode"); 141 } else if (trust instanceof TrustWay) { 142 TrustWay tw = (TrustWay) trust; 143 openAtt("trustway", "osmid=\""+String.valueOf(osm.getUniqueId())+"\""); 144 writeTags(tw); 145 writeSegments(tw); 146 closeln("trustway"); 147 } else if (trust instanceof TrustRelation) { 148 TrustRelation tr = (TrustRelation) trust; 149 openAtt("trustrelation", "osmid=\""+String.valueOf(osm.getUniqueId())+"\""); 150 writeTags(tr); 151 writeMembers(tr); 152 closeln("trustrelation"); 153 } 154 155 // openAtt("trustitem", "osmid=\""+String.valueOf(osm.getUniqueId())+"\" type=\""+osm.getType().getAPIName()+"\""); 156 157 } 158 } 159 160 private void openln(String tag) { 161 open(tag); 162 out.println(); 163 } 164 165 private void open(String tag) { 166 out.print(indent + "<" + tag + ">"); 167 indent += " "; 168 } 169 170 private void openAtt(String tag, String attributes) { 171 out.println(indent + "<" + tag + " " + attributes + ">"); 172 indent += " "; 173 } 174 175 /*private void inline(String tag, String attributes) { 176 out.println(indent + "<" + tag + " " + attributes + " />"); 177 }*/ 178 179 private void close(String tag) { 180 indent = indent.substring(2); 181 out.print(indent + "</" + tag + ">"); 182 } 183 184 private void closeln(String tag) { 185 close(tag); 186 out.println(); 187 } 188 189 /** 190 * if content not null, open tag, write encoded content, and close tag 191 * else do nothing. 192 */ 193 private void simpleTag(String tag, String content) { 194 if (content != null && content.length() > 0) { 195 open(tag); 196 out.print(encode(content)); 197 //out.print(content); 198 out.println("</" + tag + ">"); 199 indent = indent.substring(2); 200 } 201 } 202 202 203 203 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/NameGenerator.java
r26055 r30724 49 49 */ 50 50 public class NameGenerator { 51 ArrayList<String> pre = new ArrayList<String>();52 ArrayList<String> mid = new ArrayList<String>();53 ArrayList<String> sur = new ArrayList<String>();54 55 final private static char[] vocals = {'a', 'e', 'i', 'o', 'u', 'ä', 'ö', 'õ', 'ü', 'y'};56 final private static char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p','q', 'r', 's', 't', 'v', 'w', 'x', 'y'};57 58 private String fileName;59 60 /**61 * Create new random name generator object. refresh() is automatically called.62 * @param fileName insert file name, where syllables are located63 * @throws IOException64 */65 public NameGenerator(String fileName) throws IOException{66 this.fileName = fileName;67 refresh();68 }69 70 /**71 * Change the file. refresh() is automatically called during the process.72 * @param fileName insert the file name, where syllables are located.73 * @throws IOException74 */75 public void changeFile(String fileName) throws IOException{76 if(fileName == null) throw new IOException("File name cannot be null");77 this.fileName = fileName;78 refresh();79 }80 81 /**82 * Refresh names from file. No need to call that method, if you are not changing the file during the operation of program, as this method83 * is called every time file name is changed or new NameGenerator object created.84 * @throws IOException85 */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){115 return s.substring(0,1).toUpperCase().concat(s.substring(1));116 }117 118 private boolean containsConsFirst(ArrayList<String> array){119 for(String s: array){120 if(consonantFirst(s)) return true;121 }122 return false;123 }124 125 private boolean containsVocFirst(ArrayList<String> array){126 for(String s: array){127 if(vocalFirst(s)) return true;128 }129 return false;130 }131 132 private boolean allowCons(ArrayList<String> array){133 for(String s: array){134 if(hatesPreviousVocals(s) || hatesPreviousConsonants(s) == false) return true;135 }136 return false;137 }138 139 private boolean allowVocs(ArrayList<String> array){140 for(String s: array){141 if(hatesPreviousConsonants(s) || hatesPreviousVocals(s) == false) return true;142 }143 return false;144 }145 146 private boolean expectsVocal(String s){147 if(s.substring(1).contains("+v")) return true;148 else return false;149 }150 private boolean expectsConsonant(String s){151 if(s.substring(1).contains("+c")) return true;152 else return false;153 }154 private boolean hatesPreviousVocals(String s){155 if(s.substring(1).contains("-c")) return true;156 else return false;157 }158 private boolean hatesPreviousConsonants(String s){159 if(s.substring(1).contains("-v")) return true;160 else return false;161 }162 163 private String pureSyl(String s){164 s = s.trim();165 if(s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1);166 return s.split(" ")[0];167 }168 169 private boolean vocalFirst(String s){170 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(0)).toLowerCase()));171 }172 173 private boolean consonantFirst(String s){174 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(0)).toLowerCase()));175 }176 177 private boolean vocalLast(String s){178 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase()));179 }180 181 private boolean consonantLast(String s){182 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase()));183 }184 185 186 /**187 * Compose a new name.188 * @param syls The number of syllables used in name.189 * @return Returns composed name as a String190 * @throws RuntimeException when logical mistakes are detected inside chosen file, and program is unable to complete the name.191 */192 public String compose(int syls){193 if(syls > 2 && mid.size() == 0) throw new RuntimeException("You are trying to create a name with more than 3 parts, which requires middle parts, " +194 "which you have none in the file "+fileName+". You should add some. Every word, which doesn't have + or - for a prefix is counted as a middle part.");195 if(pre.size() == 0) throw new RuntimeException("You have no prefixes to start creating a name. add some and use \"-\" prefix, to identify it as a prefix for a name. (example: -asd)");196 if(sur.size() == 0) throw new RuntimeException("You have no suffixes to end a name. add some and use \"+\" prefix, to identify it as a suffix for a name. (example: +asd)");197 if(syls < 1) throw new RuntimeException("compose(int syls) can't have less than 1 syllable");198 int expecting = 0; // 1 for vocal, 2 for consonant199 int last = 0; // 1 for vocal, 2 for consonant200 String name;201 int a = (int)(Math.random() * pre.size());202 203 if(vocalLast(pureSyl(pre.get(a)))) last = 1;204 else last = 2;205 206 if(syls > 2){207 if(expectsVocal(pre.get(a))){208 expecting = 1;209 if(containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " +210 "but there is none. You should add one, or remove requirement for one.. ");211 }212 if(expectsConsonant(pre.get(a))){213 expecting = 2;214 if(containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " +215 "but there is none. You should add one, or remove requirement for one.. ");216 }217 }218 else{219 if(expectsVocal(pre.get(a))){220 expecting = 1;221 if(containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " +222 "but there is none. You should add one, or remove requirement for one.. ");223 }224 if(expectsConsonant(pre.get(a))){225 expecting = 2;226 if(containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " +227 "but there is none. You should add one, or remove requirement for one.. ");228 }229 }230 if(vocalLast(pureSyl(pre.get(a))) && allowVocs(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a vocal, " +231 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" +232 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all.");233 234 if(consonantLast(pureSyl(pre.get(a))) && allowCons(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a consonant, " +235 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" +236 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all.");237 238 int b[] = new int[syls];239 for(int i = 0; i<b.length-2; i++){240 241 do{242 b[i] = (int)(Math.random() * mid.size());243 //System.out.println("exp " +expecting+" vocalF:"+vocalFirst(mid.get(b[i]))+" syl: "+mid.get(b[i]));244 }245 while(expecting == 1 && vocalFirst(pureSyl(mid.get(b[i]))) == false || expecting == 2 && consonantFirst(pureSyl(mid.get(b[i]))) == false246 || last == 1 && hatesPreviousVocals(mid.get(b[i])) || last == 2 && hatesPreviousConsonants(mid.get(b[i])));247 248 expecting = 0;249 if(expectsVocal(mid.get(b[i]))){250 expecting = 1;251 if(i < b.length-3 && containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " +252 "but there is none. You should add one, or remove requirement for one.. ");253 if(i == b.length-3 && containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " +254 "but there is none. You should add one, or remove requirement for one.. ");255 }256 if(expectsConsonant(mid.get(b[i]))){257 expecting = 2;258 if(i < b.length-3 && containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " +259 "but there is none. You should add one, or remove requirement for one.. ");260 if(i == b.length-3 && containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " +261 "but there is none. You should add one, or remove requirement for one.. ");262 }263 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a vocal, " +264 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +265 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all.");266 267 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a consonant, " +268 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +269 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all.");270 if(i == b.length-3){271 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a vocal, " +272 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +273 "means there should be a suffix available, that has \"-v\" requirement or no requirements for previous syllables at all.");274 275 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a consonant, " +276 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +277 "means there should be a suffix available, that has \"-c\" requirement or no requirements for previous syllables at all.");278 }279 if(vocalLast(pureSyl(mid.get(b[i])))) last = 1;280 else last = 2;281 }282 283 int c;284 do{285 c = (int)(Math.random() * sur.size());286 }287 while(expecting == 1 && vocalFirst(pureSyl(sur.get(c))) == false || expecting == 2 && consonantFirst(pureSyl(sur.get(c))) == false288 || last == 1 && hatesPreviousVocals(sur.get(c)) || last == 2 && hatesPreviousConsonants(sur.get(c)));289 290 name = upper(pureSyl(pre.get(a).toLowerCase()));291 for(int i = 0; i<b.length-2; i++){292 name = name.concat(pureSyl(mid.get(b[i]).toLowerCase()));293 }294 if(syls > 1)295 name = name.concat(pureSyl(sur.get(c).toLowerCase()));296 return name;297 }51 ArrayList<String> pre = new ArrayList<>(); 52 ArrayList<String> mid = new ArrayList<>(); 53 ArrayList<String> sur = new ArrayList<>(); 54 55 final private static char[] vocals = {'a', 'e', 'i', 'o', 'u', 'ä', 'ö', 'õ', 'ü', 'y'}; 56 final private static char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y'}; 57 58 private String fileName; 59 60 /** 61 * Create new random name generator object. refresh() is automatically called. 62 * @param fileName insert file name, where syllables are located 63 * @throws IOException 64 */ 65 public NameGenerator(String fileName) throws IOException{ 66 this.fileName = fileName; 67 refresh(); 68 } 69 70 /** 71 * Change the file. refresh() is automatically called during the process. 72 * @param fileName insert the file name, where syllables are located. 73 * @throws IOException 74 */ 75 public void changeFile(String fileName) throws IOException{ 76 if(fileName == null) throw new IOException("File name cannot be null"); 77 this.fileName = fileName; 78 refresh(); 79 } 80 81 /** 82 * Refresh names from file. No need to call that method, if you are not changing the file during the operation of program, as this method 83 * is called every time file name is changed or new NameGenerator object created. 84 * @throws IOException 85 */ 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){ 115 return s.substring(0,1).toUpperCase().concat(s.substring(1)); 116 } 117 118 private boolean containsConsFirst(ArrayList<String> array){ 119 for(String s: array){ 120 if(consonantFirst(s)) return true; 121 } 122 return false; 123 } 124 125 private boolean containsVocFirst(ArrayList<String> array){ 126 for(String s: array){ 127 if(vocalFirst(s)) return true; 128 } 129 return false; 130 } 131 132 private boolean allowCons(ArrayList<String> array){ 133 for(String s: array){ 134 if(hatesPreviousVocals(s) || hatesPreviousConsonants(s) == false) return true; 135 } 136 return false; 137 } 138 139 private boolean allowVocs(ArrayList<String> array){ 140 for(String s: array){ 141 if(hatesPreviousConsonants(s) || hatesPreviousVocals(s) == false) return true; 142 } 143 return false; 144 } 145 146 private boolean expectsVocal(String s){ 147 if(s.substring(1).contains("+v")) return true; 148 else return false; 149 } 150 private boolean expectsConsonant(String s){ 151 if(s.substring(1).contains("+c")) return true; 152 else return false; 153 } 154 private boolean hatesPreviousVocals(String s){ 155 if(s.substring(1).contains("-c")) return true; 156 else return false; 157 } 158 private boolean hatesPreviousConsonants(String s){ 159 if(s.substring(1).contains("-v")) return true; 160 else return false; 161 } 162 163 private String pureSyl(String s){ 164 s = s.trim(); 165 if(s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1); 166 return s.split(" ")[0]; 167 } 168 169 private boolean vocalFirst(String s){ 170 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(0)).toLowerCase())); 171 } 172 173 private boolean consonantFirst(String s){ 174 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(0)).toLowerCase())); 175 } 176 177 private boolean vocalLast(String s){ 178 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase())); 179 } 180 181 private boolean consonantLast(String s){ 182 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase())); 183 } 184 185 186 /** 187 * Compose a new name. 188 * @param syls The number of syllables used in name. 189 * @return Returns composed name as a String 190 * @throws RuntimeException when logical mistakes are detected inside chosen file, and program is unable to complete the name. 191 */ 192 public String compose(int syls){ 193 if(syls > 2 && mid.size() == 0) throw new RuntimeException("You are trying to create a name with more than 3 parts, which requires middle parts, " + 194 "which you have none in the file "+fileName+". You should add some. Every word, which doesn't have + or - for a prefix is counted as a middle part."); 195 if(pre.size() == 0) throw new RuntimeException("You have no prefixes to start creating a name. add some and use \"-\" prefix, to identify it as a prefix for a name. (example: -asd)"); 196 if(sur.size() == 0) throw new RuntimeException("You have no suffixes to end a name. add some and use \"+\" prefix, to identify it as a suffix for a name. (example: +asd)"); 197 if(syls < 1) throw new RuntimeException("compose(int syls) can't have less than 1 syllable"); 198 int expecting = 0; // 1 for vocal, 2 for consonant 199 int last = 0; // 1 for vocal, 2 for consonant 200 String name; 201 int a = (int)(Math.random() * pre.size()); 202 203 if(vocalLast(pureSyl(pre.get(a)))) last = 1; 204 else last = 2; 205 206 if(syls > 2){ 207 if(expectsVocal(pre.get(a))){ 208 expecting = 1; 209 if(containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " + 210 "but there is none. You should add one, or remove requirement for one.. "); 211 } 212 if(expectsConsonant(pre.get(a))){ 213 expecting = 2; 214 if(containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " + 215 "but there is none. You should add one, or remove requirement for one.. "); 216 } 217 } 218 else{ 219 if(expectsVocal(pre.get(a))){ 220 expecting = 1; 221 if(containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " + 222 "but there is none. You should add one, or remove requirement for one.. "); 223 } 224 if(expectsConsonant(pre.get(a))){ 225 expecting = 2; 226 if(containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " + 227 "but there is none. You should add one, or remove requirement for one.. "); 228 } 229 } 230 if(vocalLast(pureSyl(pre.get(a))) && allowVocs(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a vocal, " + 231 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" + 232 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all."); 233 234 if(consonantLast(pureSyl(pre.get(a))) && allowCons(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a consonant, " + 235 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" + 236 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all."); 237 238 int b[] = new int[syls]; 239 for(int i = 0; i<b.length-2; i++){ 240 241 do{ 242 b[i] = (int)(Math.random() * mid.size()); 243 //System.out.println("exp " +expecting+" vocalF:"+vocalFirst(mid.get(b[i]))+" syl: "+mid.get(b[i])); 244 } 245 while(expecting == 1 && vocalFirst(pureSyl(mid.get(b[i]))) == false || expecting == 2 && consonantFirst(pureSyl(mid.get(b[i]))) == false 246 || last == 1 && hatesPreviousVocals(mid.get(b[i])) || last == 2 && hatesPreviousConsonants(mid.get(b[i]))); 247 248 expecting = 0; 249 if(expectsVocal(mid.get(b[i]))){ 250 expecting = 1; 251 if(i < b.length-3 && containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " + 252 "but there is none. You should add one, or remove requirement for one.. "); 253 if(i == b.length-3 && containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " + 254 "but there is none. You should add one, or remove requirement for one.. "); 255 } 256 if(expectsConsonant(mid.get(b[i]))){ 257 expecting = 2; 258 if(i < b.length-3 && containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " + 259 "but there is none. You should add one, or remove requirement for one.. "); 260 if(i == b.length-3 && containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " + 261 "but there is none. You should add one, or remove requirement for one.. "); 262 } 263 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a vocal, " + 264 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 265 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all."); 266 267 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a consonant, " + 268 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 269 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all."); 270 if(i == b.length-3){ 271 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a vocal, " + 272 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 273 "means there should be a suffix available, that has \"-v\" requirement or no requirements for previous syllables at all."); 274 275 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a consonant, " + 276 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 277 "means there should be a suffix available, that has \"-c\" requirement or no requirements for previous syllables at all."); 278 } 279 if(vocalLast(pureSyl(mid.get(b[i])))) last = 1; 280 else last = 2; 281 } 282 283 int c; 284 do{ 285 c = (int)(Math.random() * sur.size()); 286 } 287 while(expecting == 1 && vocalFirst(pureSyl(sur.get(c))) == false || expecting == 2 && consonantFirst(pureSyl(sur.get(c))) == false 288 || last == 1 && hatesPreviousVocals(sur.get(c)) || last == 2 && hatesPreviousConsonants(sur.get(c))); 289 290 name = upper(pureSyl(pre.get(a).toLowerCase())); 291 for(int i = 0; i<b.length-2; i++){ 292 name = name.concat(pureSyl(mid.get(b[i]).toLowerCase())); 293 } 294 if(syls > 1) 295 name = name.concat(pureSyl(sur.get(c).toLowerCase())); 296 return name; 297 } 298 298 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/TrustAnalyzer.java
r26055 r30724 17 17 import org.openstreetmap.josm.plugins.trustosm.data.TrustNode; 18 18 import org.openstreetmap.josm.plugins.trustosm.data.TrustOsmPrimitive; 19 import org.openstreetmap.josm.plugins.trustosm.data.TrustRelation;20 19 import org.openstreetmap.josm.plugins.trustosm.data.TrustSignatures; 21 20 import org.openstreetmap.josm.plugins.trustosm.data.TrustWay; … … 23 22 public class TrustAnalyzer { 24 23 25 public static void showManipulationWarning(){26 JOptionPane.showMessageDialog(Main.parent, tr("The Signature is broken!"), tr("Manipulation Warning"), JOptionPane.WARNING_MESSAGE);27 }28 29 30 public static double computeReputation(TrustOsmPrimitive trust, Map<String, List<PGPSignature>> textsigs) {31 /** just for simplicity - count all valid sigs */32 int count = 0;33 for (List<PGPSignature> siglist : textsigs.values()) {34 count += siglist.size();35 }36 return count;37 }38 39 public static boolean isTagRatingValid(TrustOsmPrimitive trust, String key, String signedPlaintext) {40 /** Rating is valid if signed plaintext matches the current plaintext */41 String currentSigtext = TrustOsmPrimitive.generateTagSigtext(trust.getOsmPrimitive(),key);42 return currentSigtext.equals(signedPlaintext);43 }44 45 46 public static void checkTag(TrustOsmPrimitive trust, String key) {47 Map<String, List<PGPSignature>> validRatings = new HashMap<String, List<PGPSignature>>();48 49 TrustSignatures sigs;50 if ((sigs = trust.getSigsOnKey(key))!=null) {51 for (PGPSignature sig : sigs.getSignatures()) {52 /** Here we have a full rating53 * The first question: Is the Signature valid?54 * It could be manipulated...55 * */56 String signedPlaintext = sigs.getSigtext(sig);57 if (TrustOSMplugin.gpg.verify(signedPlaintext, sig)) {58 /** If it is valid...59 * Second question: Is the rating valid?60 */61 if (isTagRatingValid(trust,key,signedPlaintext)) {62 /** if the rating is good, we can try to compute a reputation value at the end63 * so we save the important rating stuff64 */65 if (validRatings.containsKey(signedPlaintext)) {66 validRatings.get(signedPlaintext).add(sig);67 } else {68 List<PGPSignature> l = new ArrayList<PGPSignature>();69 l.add(sig);70 validRatings.put(signedPlaintext, l);71 }72 73 //if (sigs.getStatus() == TrustSignatures.SIG_UNKNOWN) sigs.setStatus(TrustSignatures.SIG_VALID);74 } else {75 //sigs.setStatus(TrustSignatures.SIG_BROKEN);76 }77 } else {78 //sigs.setStatus(TrustSignatures.SIG_BROKEN);79 showManipulationWarning();80 }81 }82 /** now we know which ratings are valid to compute a reputation */83 sigs.setReputation(computeReputation(trust, validRatings));84 /** if all available signatures are valid we can set the TrustSignatures status to valid */85 System.out.println(validRatings.size()+":"+sigs.countSigs());86 if (validRatings.size() == 1) sigs.setStatus(TrustSignatures.SIG_VALID);87 else sigs.setStatus(TrustSignatures.SIG_BROKEN);88 }89 }90 91 92 public static boolean isNodeRatingValid(TrustNode trust, String signedPlaintext, PGPSignature sig) {93 /** Rating is valid if Node from signed plaintext is inside Tolerance given in Signature */94 Node signedNode = TrustNode.generateNodeFromSigtext(signedPlaintext);95 Node currentNode = (Node)trust.getOsmPrimitive();96 double dist = signedNode.getCoor().greatCircleDistance(currentNode.getCoor());97 98 /** is distance between signed Node and current Node inside tolerance? */99 return dist<=TrustGPG.searchTolerance(sig);100 }101 102 /**103 * Check if the ratings made for a Node are valid for the current position of that node104 * and compute reputation.105 * @param trustThe current TrustNode with its ratings106 */107 public static void checkNode(TrustNode trust) {108 Map<String, List<PGPSignature>> validRatings = new HashMap<String, List<PGPSignature>>();109 Node node = (Node)trust.getOsmPrimitive();110 TrustSignatures sigs;111 if ((sigs = trust.getNodeSigs())!=null) {112 for (String signedPlaintext : sigs.getAllPlainTexts()) {113 for (PGPSignature sig : sigs.getSignaturesByPlaintext(signedPlaintext)) {114 /** first thing: check signature */115 if (TrustOSMplugin.gpg.verify(signedPlaintext,sig)) {116 /** if signature is valid check rating */117 if (isNodeRatingValid(trust,signedPlaintext,sig)) {118 /** if the rating is good, we can try to compute a reputation value at the end119 * so we save the important rating stuff120 */121 if (validRatings.containsKey(signedPlaintext)) {122 validRatings.get(signedPlaintext).add(sig);123 } else {124 List<PGPSignature> l = new ArrayList<PGPSignature>();125 l.add(sig);126 validRatings.put(signedPlaintext, l);127 }128 129 //if (sigs.getStatus() == TrustSignatures.SIG_UNKNOWN) sigs.setStatus(TrustSignatures.SIG_VALID);130 } else {131 //sigs.setStatus(TrustSignatures.SIG_BROKEN);132 }133 134 } else {135 //sigs.setStatus(TrustSignatures.SIG_BROKEN);136 showManipulationWarning();137 }138 }139 }140 /** now we know which ratings are valid to compute a reputation */141 sigs.setReputation(computeReputation(trust, validRatings));142 /** if all available signatures are valid we can set the TrustSignatures status to valid */143 if (validRatings.size() == 1) sigs.setStatus(TrustSignatures.SIG_VALID);144 else sigs.setStatus(TrustSignatures.SIG_BROKEN);145 }146 }147 148 /**149 * Check if the ratings made for a specific WaySegment are valid for the current form of that WaySegment150 * @param trust151 * @param seg152 * @param signedPlaintext153 * @param sig154 * @return155 */156 public static boolean isSegmentRatingValid(TrustWay trust, List<Node> nodes, String signedPlaintext, PGPSignature sig) {157 /** Rating is valid if Nodes from Segment of signed plaintext are inside Tolerance given in Signature */158 List<Node> signedSegment = TrustWay.generateSegmentFromSigtext(signedPlaintext);159 160 double tolerance = TrustGPG.searchTolerance(sig);161 162 for (int i = 0; i<2; i++){163 Node signedNode = signedSegment.get(i);164 Node currentNode = nodes.get(i);165 double dist = signedNode.getCoor().greatCircleDistance(currentNode.getCoor());166 if (dist>tolerance) return false;167 }168 return true;169 }170 171 /**172 * Check if there are ratings for a current WaySegment of a TrustWay173 * and if so, compute Reputation174 * @param trust the current TrustWay175 * @param seg the current WaySegment to check for reputation176 */177 public static void checkSegment(TrustWay trust, List<Node> nodes) {178 Map<String, List<PGPSignature>> validRatings = new HashMap<String, List<PGPSignature>>();179 180 TrustSignatures sigs;181 if ((sigs = trust.getSigsOnSegment(nodes))!=null) {182 for (String signedPlaintext : sigs.getAllPlainTexts()) {183 for (PGPSignature sig : sigs.getSignaturesByPlaintext(signedPlaintext)) {184 /** first thing: check signature */185 if (TrustOSMplugin.gpg.verify(signedPlaintext,sig)) {186 /** if signature is valid check rating */187 if (isSegmentRatingValid(trust,nodes,signedPlaintext,sig)) {188 /** if the rating is good, we can try to compute a reputation value at the end189 * so we save the important rating stuff190 */191 if (validRatings.containsKey(signedPlaintext)) {192 validRatings.get(signedPlaintext).add(sig);193 } else {194 List<PGPSignature> l = new ArrayList<PGPSignature>();195 l.add(sig);196 validRatings.put(signedPlaintext, l);197 }198 199 //if (sigs.getStatus() == TrustSignatures.SIG_UNKNOWN) sigs.setStatus(TrustSignatures.SIG_VALID);200 } else {201 //sigs.setStatus(TrustSignatures.SIG_BROKEN);202 }203 204 } else {205 //sigs.setStatus(TrustSignatures.SIG_BROKEN);206 showManipulationWarning();207 }208 }209 }210 /** now we know which ratings are valid to compute a reputation */211 sigs.setReputation(computeReputation(trust, validRatings));212 /** if all available signatures are valid we can set the TrustSignatures status to valid */213 if (validRatings.size() == sigs.countSigs()) sigs.setStatus(TrustSignatures.SIG_VALID);214 else sigs.setStatus(TrustSignatures.SIG_BROKEN);215 }216 }217 218 219 public static void checkEverything(TrustOsmPrimitive trust) {220 /** check every single tag for reputation */221 for (String key : trust.getSignedKeys()){222 checkTag(trust, key);223 }224 if (trust instanceof TrustNode) {225 /** check all reputation of this single Node */226 checkNode((TrustNode) trust);227 } else if (trust instanceof TrustWay){228 TrustWay tw = (TrustWay) trust;229 /** check all reputation for every Segment of this Way */230 List<Node> wayNodes = ((Way)tw.getOsmPrimitive()).getNodes();231 for (int i=0; i<wayNodes.size()-1; i++) {232 List<Node> nodes = new ArrayList<Node>();233 nodes.add(wayNodes.get(i));234 nodes.add(wayNodes.get(i+1));235 checkSegment(tw,nodes);236 }237 238 }else if (trust instanceof TrustRelation){239 TrustRelation tr = (TrustRelation) trust;240 } 241 242 }24 public static void showManipulationWarning(){ 25 JOptionPane.showMessageDialog(Main.parent, tr("The Signature is broken!"), tr("Manipulation Warning"), JOptionPane.WARNING_MESSAGE); 26 } 27 28 29 public static double computeReputation(TrustOsmPrimitive trust, Map<String, List<PGPSignature>> textsigs) { 30 /** just for simplicity - count all valid sigs */ 31 int count = 0; 32 for (List<PGPSignature> siglist : textsigs.values()) { 33 count += siglist.size(); 34 } 35 return count; 36 } 37 38 public static boolean isTagRatingValid(TrustOsmPrimitive trust, String key, String signedPlaintext) { 39 /** Rating is valid if signed plaintext matches the current plaintext */ 40 String currentSigtext = TrustOsmPrimitive.generateTagSigtext(trust.getOsmPrimitive(),key); 41 return currentSigtext.equals(signedPlaintext); 42 } 43 44 45 public static void checkTag(TrustOsmPrimitive trust, String key) { 46 Map<String, List<PGPSignature>> validRatings = new HashMap<>(); 47 48 TrustSignatures sigs; 49 if ((sigs = trust.getSigsOnKey(key))!=null) { 50 for (PGPSignature sig : sigs.getSignatures()) { 51 /** Here we have a full rating 52 * The first question: Is the Signature valid? 53 * It could be manipulated... 54 * */ 55 String signedPlaintext = sigs.getSigtext(sig); 56 if (TrustOSMplugin.gpg.verify(signedPlaintext, sig)) { 57 /** If it is valid... 58 * Second question: Is the rating valid? 59 */ 60 if (isTagRatingValid(trust,key,signedPlaintext)) { 61 /** if the rating is good, we can try to compute a reputation value at the end 62 * so we save the important rating stuff 63 */ 64 if (validRatings.containsKey(signedPlaintext)) { 65 validRatings.get(signedPlaintext).add(sig); 66 } else { 67 List<PGPSignature> l = new ArrayList<>(); 68 l.add(sig); 69 validRatings.put(signedPlaintext, l); 70 } 71 72 //if (sigs.getStatus() == TrustSignatures.SIG_UNKNOWN) sigs.setStatus(TrustSignatures.SIG_VALID); 73 } else { 74 //sigs.setStatus(TrustSignatures.SIG_BROKEN); 75 } 76 } else { 77 //sigs.setStatus(TrustSignatures.SIG_BROKEN); 78 showManipulationWarning(); 79 } 80 } 81 /** now we know which ratings are valid to compute a reputation */ 82 sigs.setReputation(computeReputation(trust, validRatings)); 83 /** if all available signatures are valid we can set the TrustSignatures status to valid */ 84 System.out.println(validRatings.size()+":"+sigs.countSigs()); 85 if (validRatings.size() == 1) sigs.setStatus(TrustSignatures.SIG_VALID); 86 else sigs.setStatus(TrustSignatures.SIG_BROKEN); 87 } 88 } 89 90 91 public static boolean isNodeRatingValid(TrustNode trust, String signedPlaintext, PGPSignature sig) { 92 /** Rating is valid if Node from signed plaintext is inside Tolerance given in Signature */ 93 Node signedNode = TrustNode.generateNodeFromSigtext(signedPlaintext); 94 Node currentNode = (Node)trust.getOsmPrimitive(); 95 double dist = signedNode.getCoor().greatCircleDistance(currentNode.getCoor()); 96 97 /** is distance between signed Node and current Node inside tolerance? */ 98 return dist<=TrustGPG.searchTolerance(sig); 99 } 100 101 /** 102 * Check if the ratings made for a Node are valid for the current position of that node 103 * and compute reputation. 104 * @param trust The current TrustNode with its ratings 105 */ 106 public static void checkNode(TrustNode trust) { 107 Map<String, List<PGPSignature>> validRatings = new HashMap<>(); 108 //Node node = (Node)trust.getOsmPrimitive(); 109 TrustSignatures sigs; 110 if ((sigs = trust.getNodeSigs())!=null) { 111 for (String signedPlaintext : sigs.getAllPlainTexts()) { 112 for (PGPSignature sig : sigs.getSignaturesByPlaintext(signedPlaintext)) { 113 /** first thing: check signature */ 114 if (TrustOSMplugin.gpg.verify(signedPlaintext,sig)) { 115 /** if signature is valid check rating */ 116 if (isNodeRatingValid(trust,signedPlaintext,sig)) { 117 /** if the rating is good, we can try to compute a reputation value at the end 118 * so we save the important rating stuff 119 */ 120 if (validRatings.containsKey(signedPlaintext)) { 121 validRatings.get(signedPlaintext).add(sig); 122 } else { 123 List<PGPSignature> l = new ArrayList<>(); 124 l.add(sig); 125 validRatings.put(signedPlaintext, l); 126 } 127 128 //if (sigs.getStatus() == TrustSignatures.SIG_UNKNOWN) sigs.setStatus(TrustSignatures.SIG_VALID); 129 } else { 130 //sigs.setStatus(TrustSignatures.SIG_BROKEN); 131 } 132 133 } else { 134 //sigs.setStatus(TrustSignatures.SIG_BROKEN); 135 showManipulationWarning(); 136 } 137 } 138 } 139 /** now we know which ratings are valid to compute a reputation */ 140 sigs.setReputation(computeReputation(trust, validRatings)); 141 /** if all available signatures are valid we can set the TrustSignatures status to valid */ 142 if (validRatings.size() == 1) sigs.setStatus(TrustSignatures.SIG_VALID); 143 else sigs.setStatus(TrustSignatures.SIG_BROKEN); 144 } 145 } 146 147 /** 148 * Check if the ratings made for a specific WaySegment are valid for the current form of that WaySegment 149 * @param trust 150 * @param seg 151 * @param signedPlaintext 152 * @param sig 153 * @return 154 */ 155 public static boolean isSegmentRatingValid(TrustWay trust, List<Node> nodes, String signedPlaintext, PGPSignature sig) { 156 /** Rating is valid if Nodes from Segment of signed plaintext are inside Tolerance given in Signature */ 157 List<Node> signedSegment = TrustWay.generateSegmentFromSigtext(signedPlaintext); 158 159 double tolerance = TrustGPG.searchTolerance(sig); 160 161 for (int i = 0; i<2; i++){ 162 Node signedNode = signedSegment.get(i); 163 Node currentNode = nodes.get(i); 164 double dist = signedNode.getCoor().greatCircleDistance(currentNode.getCoor()); 165 if (dist>tolerance) return false; 166 } 167 return true; 168 } 169 170 /** 171 * Check if there are ratings for a current WaySegment of a TrustWay 172 * and if so, compute Reputation 173 * @param trust the current TrustWay 174 * @param seg the current WaySegment to check for reputation 175 */ 176 public static void checkSegment(TrustWay trust, List<Node> nodes) { 177 Map<String, List<PGPSignature>> validRatings = new HashMap<>(); 178 179 TrustSignatures sigs; 180 if ((sigs = trust.getSigsOnSegment(nodes))!=null) { 181 for (String signedPlaintext : sigs.getAllPlainTexts()) { 182 for (PGPSignature sig : sigs.getSignaturesByPlaintext(signedPlaintext)) { 183 /** first thing: check signature */ 184 if (TrustOSMplugin.gpg.verify(signedPlaintext,sig)) { 185 /** if signature is valid check rating */ 186 if (isSegmentRatingValid(trust,nodes,signedPlaintext,sig)) { 187 /** if the rating is good, we can try to compute a reputation value at the end 188 * so we save the important rating stuff 189 */ 190 if (validRatings.containsKey(signedPlaintext)) { 191 validRatings.get(signedPlaintext).add(sig); 192 } else { 193 List<PGPSignature> l = new ArrayList<>(); 194 l.add(sig); 195 validRatings.put(signedPlaintext, l); 196 } 197 198 //if (sigs.getStatus() == TrustSignatures.SIG_UNKNOWN) sigs.setStatus(TrustSignatures.SIG_VALID); 199 } else { 200 //sigs.setStatus(TrustSignatures.SIG_BROKEN); 201 } 202 203 } else { 204 //sigs.setStatus(TrustSignatures.SIG_BROKEN); 205 showManipulationWarning(); 206 } 207 } 208 } 209 /** now we know which ratings are valid to compute a reputation */ 210 sigs.setReputation(computeReputation(trust, validRatings)); 211 /** if all available signatures are valid we can set the TrustSignatures status to valid */ 212 if (validRatings.size() == sigs.countSigs()) sigs.setStatus(TrustSignatures.SIG_VALID); 213 else sigs.setStatus(TrustSignatures.SIG_BROKEN); 214 } 215 } 216 217 218 public static void checkEverything(TrustOsmPrimitive trust) { 219 /** check every single tag for reputation */ 220 for (String key : trust.getSignedKeys()){ 221 checkTag(trust, key); 222 } 223 if (trust instanceof TrustNode) { 224 /** check all reputation of this single Node */ 225 checkNode((TrustNode) trust); 226 } else if (trust instanceof TrustWay){ 227 TrustWay tw = (TrustWay) trust; 228 /** check all reputation for every Segment of this Way */ 229 List<Node> wayNodes = ((Way)tw.getOsmPrimitive()).getNodes(); 230 for (int i=0; i<wayNodes.size()-1; i++) { 231 List<Node> nodes = new ArrayList<>(); 232 nodes.add(wayNodes.get(i)); 233 nodes.add(wayNodes.get(i+1)); 234 checkSegment(tw,nodes); 235 } 236 237 } /*else if (trust instanceof TrustRelation){ 238 TrustRelation tr = (TrustRelation) trust; 239 }*/ 240 241 } 243 242 } -
applications/editors/josm/plugins/trustosm/src/org/openstreetmap/josm/plugins/trustosm/util/TrustGPG.java
r26345 r30724 81 81 public class TrustGPG { 82 82 83 // private GnuPG gpg; 84 private char[] password; 85 private PGPSecretKeyRingCollection pgpSec; 86 private PGPPublicKeyRingCollection pgpPub; 87 private static int digest = PGPUtil.SHA1; 88 private PGPSecretKey pgpSecKey; 89 public boolean keepkey = false; 90 91 public static final String NOTATION_DATA_KEY = "trustosm@openstreetmap.org"; 92 93 public TrustGPG() { 94 Security.addProvider(new BouncyCastleProvider()); 95 try { 96 readGpgFiles(); 97 } catch (Exception e) { 98 // TODO Auto-generated catch block 99 e.printStackTrace(); 100 } 101 } 102 103 public PGPPublicKey getPublicKeyFromRing(long keyID) { 104 try { 105 if (pgpPub.contains(keyID)) 106 return pgpPub.getPublicKey(keyID); 107 else if (pgpSec.contains(keyID)) 108 return pgpSec.getSecretKey(keyID).getPublicKey(); 109 } catch (PGPException e) { 110 System.err.println("Could not read a PGPPublic key from your KeyRingCollectionFile. Stacktrace:"); 111 e.printStackTrace(); 112 } 113 return null; 114 } 115 116 public static String secKeytoString(PGPSecretKey k) { 117 String keyText = "0x"+Long.toHexString(k.getKeyID()).substring(8).toUpperCase() + " "; 118 // keyText = new String(Hex.encode(sigKey.getPublicKey().getFingerprint()),"UTF-8") + " "; 119 Iterator iter = k.getUserIDs(); 120 if (iter.hasNext()) { 121 keyText += (String)iter.next(); 122 } 123 /* iter = sigKey.getUserIDs(); 124 while (iter.hasNext()) { 125 keyText += (String)iter.next() + "; "; 126 } 127 */ 128 return keyText.trim(); 129 } 130 131 private void readSecretKey() { 132 133 // if there is no KeyRingCollection we have to create a new one 134 if (pgpSec == null) { 135 try { 136 generateKey(); 137 } catch (Exception e) { 138 System.err.println("GPG Key Ring File could not be created in: "+Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 139 } 140 } 141 // 142 // we just loop through the collection till we find a key suitable for encryption, in the real 143 // world you would probably want to be a bit smarter about this. 144 // 145 if (keepkey) return; 146 147 final ArrayList<PGPSecretKey> sigKeys = new ArrayList<PGPSecretKey>(); 148 149 // 150 // iterate through the key rings. 151 // 152 Iterator rIt = pgpSec.getKeyRings(); 153 154 while (rIt.hasNext()) { 155 156 PGPSecretKeyRing kRing = (PGPSecretKeyRing)rIt.next(); 157 Iterator kIt = kRing.getSecretKeys(); 158 159 while (kIt.hasNext()) { 160 PGPSecretKey k = (PGPSecretKey)kIt.next(); 161 162 if (k.isSigningKey()) { 163 sigKeys.add(k); 164 } 165 } 166 } 167 168 169 Iterator<PGPSecretKey> skIt = sigKeys.iterator(); 170 171 final Vector<String> keys = new Vector<String>(); 172 173 while (skIt.hasNext()) { 174 PGPSecretKey sigKey = skIt.next(); 175 keys.add(secKeytoString(sigKey)); 176 } 177 178 JPanel p = new JPanel(); 179 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); 180 Dimension d = new Dimension(0,20); 181 182 JLabel head = new JLabel(tr("Select a signing key from your keyring-file:")); 183 head.setAlignmentX(Component.LEFT_ALIGNMENT); 184 p.add(head); 185 186 final JComboBox keyBox = new JComboBox(keys); 187 keyBox.setAlignmentX(Component.LEFT_ALIGNMENT); 188 p.add(keyBox); 189 190 JCheckBox keepkeyBox = new JCheckBox(tr("Don''t ask again for the key")); 191 keepkeyBox.setAlignmentX(Component.LEFT_ALIGNMENT); 192 p.add(keepkeyBox); 193 194 JButton detailsButton = new JButton(tr("Details"), ImageProvider.get("keydetails")); 195 detailsButton.setAlignmentX(Component.LEFT_ALIGNMENT); 196 detailsButton.addActionListener(new ActionListener(){ 197 198 @Override 199 public void actionPerformed(ActionEvent arg0) { 200 PGPSecretKey sk = sigKeys.get(keyBox.getSelectedIndex()); 201 showKeyDetails(getPublicKeyFromRing(sk.getKeyID())); 202 }}); 203 p.add(detailsButton); 204 205 JCheckBox random = new JCheckBox(tr("Use a random key from this list")); 206 random.setAlignmentX(Component.LEFT_ALIGNMENT); 207 p.add(random); 208 209 p.add(Box.createRigidArea(d)); 210 211 JButton createButton = new JButton(tr("Create new Key"), ImageProvider.get("key")); 212 createButton.setAlignmentX(Component.LEFT_ALIGNMENT); 213 createButton.addActionListener(new ActionListener(){ 214 215 @Override 216 public void actionPerformed(ActionEvent arg0) { 217 try { 218 PGPSecretKey secKey = generateKey(); 219 if (secKey != null) { 220 keyBox.addItem(secKeytoString(secKey)); 221 sigKeys.add(secKey); 222 } 223 } catch (NoSuchAlgorithmException e) { 224 // TODO Auto-generated catch block 225 e.printStackTrace(); 226 } catch (NoSuchProviderException e) { 227 // TODO Auto-generated catch block 228 e.printStackTrace(); 229 } catch (FileNotFoundException e) { 230 // TODO Auto-generated catch block 231 e.printStackTrace(); 232 } catch (PGPException e) { 233 // TODO Auto-generated catch block 234 e.printStackTrace(); 235 } catch (IOException e) { 236 // TODO Auto-generated catch block 237 e.printStackTrace(); 238 } 239 240 }}); 241 p.add(createButton); 242 p.add(Box.createRigidArea(d)); 243 244 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Select a Key to sign"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, ImageProvider.get("keyring"), null, null); 245 246 if (n == JOptionPane.OK_OPTION) { 247 keepkey = keepkeyBox.isSelected(); 248 if (random.isSelected()) { 249 Random r = new Random(); 250 pgpSecKey = sigKeys.get(r.nextInt(sigKeys.size()-1)); 251 } else { 252 pgpSecKey = sigKeys.get(keyBox.getSelectedIndex()); 253 } 254 } else { 255 pgpSecKey = null; 256 } 257 //String selection = (String) JOptionPane.showInputDialog(null, tr("Select a Key to sign"),tr("Secret Key Choice"), JOptionPane.OK_CANCEL_OPTION, null, keys, keys[0]); 258 259 //System.out.println(selection); 260 261 // return pgpSecKey; 262 } 263 264 public void readGpgFiles() throws PGPException, IOException, NoSuchAlgorithmException, NoSuchProviderException { 265 FileInputStream pubIn; 266 FileInputStream secIn; 267 try { 268 pubIn = new FileInputStream(Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 269 secIn = new FileInputStream(Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/pubring.gpg"); 270 //pubIn = new FileInputStream("/tmp/secring.gpg"); 271 //secIn = new FileInputStream("/tmp/pubring.gpg"); 272 pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(pubIn)); 273 pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(secIn)); 274 } catch (FileNotFoundException e) { 275 System.err.println("No gpg files found in "+Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 276 pgpSec = null; 277 pgpPub = null; 278 } 279 280 } 281 282 public void writeGpgFiles() throws FileNotFoundException, IOException { 283 FileOutputStream pubOut = new FileOutputStream(Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/pubring.gpg"); 284 FileOutputStream secOut = new FileOutputStream(Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 285 pgpSec.encode(secOut); 286 pgpPub.encode(pubOut); 287 pubOut.flush(); 288 secOut.flush(); 289 pubOut.close(); 290 secOut.close(); 291 } 292 293 294 295 public void getPasswordfromUser() { 296 297 final JPasswordField passwordField = new JPasswordField(); 298 JOptionPane jop = new JOptionPane(passwordField, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, ImageProvider.get("lock")); 299 JDialog dialog = jop.createDialog("Password:"); 300 dialog.addComponentListener(new ComponentAdapter(){ 301 @Override 302 public void componentShown(ComponentEvent e){ 303 passwordField.requestFocusInWindow(); 304 } 305 }); 306 dialog.setVisible(true); 307 int result = (Integer)jop.getValue(); 308 dialog.dispose(); 309 if(result == JOptionPane.OK_OPTION){ 310 password = passwordField.getPassword(); 311 } 312 313 314 /*final JPasswordField passwordField = new JPasswordField(10); 315 JOptionPane.showMessageDialog(Main.parent, passwordField, "Enter password", JOptionPane.OK_OPTION, ImageProvider.get("lock")); 316 password = passwordField.getPassword(); 317 */ 318 } 319 /* 320 public void checkTag(TrustOsmPrimitive trust, String key) { 321 String sigtext = TrustOsmPrimitive.generateTagSigtext(trust.getOsmPrimitive(),key); 322 TrustSignatures sigs; 323 if ((sigs = trust.getSigsOnKey(key))!=null) 324 for (PGPSignature sig : sigs.getSignatures()) { 325 trust.updateTagSigStatus(key, verify(sigtext,sig)? TrustSignatures.SIG_VALID : TrustSignatures.SIG_BROKEN); 326 } 327 } 328 329 330 331 /* public void checkAll(TrustOsmPrimitive trust) { 332 OsmPrimitive osm = trust.getOsmPrimitive(); 333 for (String key : osm.keySet()) { 334 checkTag(trust, key); 335 } 336 337 if(osm instanceof Node) { 338 checkNode((TrustNode) trust); 339 } else if(osm instanceof Way) { 340 /* Iterator<Node> iter = ((Way)osm).getNodes().iterator(); 341 while (iter.hasNext()) { 342 checkNode(trust, iter.next()); 343 }/ 344 } else if(osm instanceof Relation) { 345 346 } 347 } 348 */ 349 350 public void invalidIDWarning(OsmPrimitive osm) { 351 JOptionPane.showMessageDialog(Main.parent, tr("The object with the ID \"{0}\" ({1}) is newly created.\nYou can not sign it, because the signature would lose the ID-Reference after uploading it to the OSM-server.",osm.getUniqueId(),osm.toString()), tr("Signing canceled!"), JOptionPane.ERROR_MESSAGE); 352 } 353 /* 354 public TrustOsmPrimitive signGeometry(TrustOsmPrimitive trust) { 355 PGPSignatureSubpacketGenerator spGen = chooseAccuracy(); 356 PGPSignature s; 357 Node node; 358 OsmPrimitive osm = trust.getOsmPrimitive(); 359 if (osm.isNew()) { 360 invalidIDWarning(osm); 361 return trust; 362 } 363 if(osm instanceof Node) { 364 s = signNode(osm,(Node)osm, spGen); 365 if (s != null) ((TrustNode)trust).storeNodeSig(s); 366 } else if(osm instanceof Way) { 367 Iterator<Node> iter = ((Way)osm).getNodes().iterator(); 368 while (iter.hasNext()) { 369 node = iter.next(); 370 s = signNode(osm,node,spGen); 371 if (s != null) ((TrustNode)trust).storeNodeSig(s); 372 } 373 } else if(osm instanceof Relation) { 374 375 } 376 return trust; 377 }*/ 378 379 public TrustWay signWay(TrustWay trust) { 380 PGPSignature s; 381 Way w = (Way) trust.getOsmPrimitive(); 382 if (w.isNew()) { 383 invalidIDWarning(w); 384 return trust; 385 } 386 /* 387 List<Node> nodes = w.getNodes(); 388 s = signSegment(trust,nodes); 389 if (s != null) trust.storeSegmentSig(nodes,s); 390 */ 391 List<Node> wayNodes = w.getNodes(); 392 for (int i=0; i<wayNodes.size()-1; i++) { 393 List<Node> nodes = new ArrayList<Node>(); 394 nodes.add(wayNodes.get(i)); 395 nodes.add(wayNodes.get(i+1)); 396 s = signSegment(trust,nodes); 397 if (s != null) trust.storeSegmentSig(nodes,s); 398 } 399 400 return trust; 401 } 402 403 public PGPSignature signSegment(TrustWay trust, List<Node> nodes) { 404 Way w = (Way) trust.getOsmPrimitive(); 405 if (w.isNew()) { 406 invalidIDWarning(w); 407 return null; 408 } 409 String tosign = TrustWay.generateSegmentSigtext(trust,nodes); 410 PGPSignatureSubpacketGenerator spGen = chooseAccuracy(); 411 return sign(tosign,spGen); 412 } 413 414 public PGPSignature signNode(Node node) { 415 PGPSignatureSubpacketGenerator spGen = chooseAccuracy(); 416 return signNode(node,spGen); 417 } 418 419 public PGPSignature signNode(Node node, PGPSignatureSubpacketGenerator spGen) { 420 if (node.isNew()) { 421 invalidIDWarning(node); 422 return null; 423 } 424 String tosign = TrustNode.generateNodeSigtext(node); 425 return sign(tosign,spGen); 426 } 427 428 public boolean signTag(TrustOsmPrimitive trust, String key) { 429 OsmPrimitive osm = trust.getOsmPrimitive(); 430 if (osm.isNew()) { 431 invalidIDWarning(osm); 432 return false; 433 } 434 PGPSignature s; 435 String tosign = TrustOsmPrimitive.generateTagSigtext(osm,key); 436 //s = sign(tosign); 437 s = sign(tosign,chooseInformationSource()); 438 if (s != null) { 439 trust.storeTagSig(key, s); 440 return true; 441 } 442 return false; 443 } 444 445 /** 446 * Search in a given Signature for Tolerance information. 447 * @param sig 448 * @return found tolerance as double or 0 if no Tolerance is given 449 */ 450 451 public static double searchTolerance(PGPSignature sig) { 452 /** Take the first NotationData packet that seems to have Tolerance information */ 453 for (NotationData nd : sig.getHashedSubPackets().getNotationDataOccurences()){ 454 if (nd.getNotationName().equals(TrustGPG.NOTATION_DATA_KEY)) { 455 String notation = nd.getNotationValue(); 456 Pattern p = Pattern.compile("^Tolerance:(\\d*\\.?\\d*)m"); 457 Matcher m = p.matcher(notation); 458 if (m.matches()) { // we found a valid Tolerance 459 return Double.parseDouble(m.group(1)); 460 } 461 } 462 } 463 return 0; 464 } 465 466 public PGPSignatureSubpacketGenerator chooseAccuracy() { 467 PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); 468 JPanel p = new JPanel(new GridBagLayout()); 469 p.add(new JLabel(tr("Please give a tolerance in meters")),GBC.eol()); 470 471 JFormattedTextField meters = new JFormattedTextField(NumberFormat.getNumberInstance()); 472 meters.setValue(new Double(10)); 473 meters.setColumns(5); 474 475 p.add(meters,GBC.std()); 476 p.add(new JLabel(tr("meters")),GBC.eol()); 477 478 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Accuracy"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 479 480 if (n == JOptionPane.OK_OPTION) { 481 spGen.setNotationData(false, true, TrustGPG.NOTATION_DATA_KEY, "Tolerance:"+meters.getValue()+"m"); 482 return spGen; 483 } 484 return null; 485 } 486 487 public PGPSignatureSubpacketGenerator chooseInformationSource() { 488 PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); 489 JPanel p = new JPanel(new GridBagLayout()); 490 p.add(new JLabel(tr("Select as much as you like:")),GBC.eol()); 491 492 JCheckBox survey = new JCheckBox(tr("Survey")); 493 p.add(survey,GBC.eol()); 494 495 JCheckBox aerial = new JCheckBox(tr("Aerial Photography")); 496 p.add(aerial,GBC.eol()); 497 498 JCheckBox web = new JCheckBox(tr("Web Recherche")); 499 p.add(web,GBC.eol()); 500 501 JCheckBox trusted = new JCheckBox(tr("Trusted persons told me")); 502 p.add(trusted,GBC.eol()); 503 504 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Which source did you use?"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 505 506 if (n == JOptionPane.OK_OPTION) { 507 String sources = "Sources:"; 508 if (survey.isSelected()) sources += ":survey"; 509 if (aerial.isSelected()) sources += ":aerial"; 510 if (web.isSelected()) sources += ":web"; 511 if (trusted.isSelected()) sources += ":trusted"; 512 spGen.setNotationData(false, true, TrustGPG.NOTATION_DATA_KEY, sources); 513 return spGen; 514 } 515 return null; 516 } 517 518 public PGPSignature sign(String tosign) { 519 PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); 520 return sign(tosign,spGen); 521 } 522 523 public PGPSignature sign(String tosign, PGPSignatureSubpacketGenerator spGen) { 524 525 if (spGen == null) return null; 526 PGPSignature sig; 527 try{ 528 529 readSecretKey(); 530 if (pgpSec == null) return null; 531 532 if (password == null) { 533 getPasswordfromUser(); 534 } 535 536 PGPPrivateKey pgpPrivKey = pgpSecKey.extractPrivateKey(password, "BC"); 537 PGPSignatureGenerator sGen = new PGPSignatureGenerator(pgpSecKey.getPublicKey().getAlgorithm(), digest, "BC"); 538 sGen.initSign(PGPSignature.CANONICAL_TEXT_DOCUMENT, pgpPrivKey); 539 540 Iterator it = pgpSecKey.getPublicKey().getUserIDs(); 541 if (it.hasNext()) { 542 spGen.setSignerUserID(false, (String)it.next()); 543 } 544 sGen.setHashedSubpackets(spGen.generate()); 545 sGen.update(tosign.getBytes(Charset.forName("UTF-8"))); 546 sig = sGen.generate(); 547 //System.out.println(new String(sGen.generateOnePassVersion(false).getEncoded(),Charset.forName("UTF-8"))); 548 //writeSignatureToFile(sig, tosign, new FileOutputStream("/tmp/sigtest.asc")); 549 //sig.encode(new BCPGOutputStream(new ArmoredOutputStream(new FileOutputStream("/tmp/sigtest.asc")))); 550 return sig; 551 }catch (Exception e){//Catch exception if any 552 System.err.println("PGP Signing Error: " + e.getMessage()); 553 } 554 555 556 /* String seckeys = gpg.listSecretKeys()? gpg.getResult() : "GPG-ERROR: " + gpg.getErrorString(); 557 System.out.println("Die gelisteten keys sehen so aus:\n"+seckeys); 558 String[] keys = seckeys.split("\n"); 559 System.out.println("Das Array hat so viele einträge:"+keys.length); 560 if (keys.length <= 1) { 561 System.out.println("Auf auf zum lustigen generieren!"); 562 generateKey(); 563 } 564 System.out.println("Achtung die Errorausgabe sieht so aus:\n"+gpg.getErrorString()); 565 String sig = gpg.sign(tosign, password)? gpg.getResult() : "GPG-ERROR: " + gpg.getErrorString(); 566 */ 567 568 569 return null; 570 } 571 572 public boolean verify(String sigtext, PGPSignature sig) { 573 /* if (gpg.verifySignature(sig)) { 574 success = trust.updateSigStatus(key, gpg.getResult().equals(sigtext)? TrustSignatures.SIG_VALID : TrustSignatures.SIG_BROKEN); 575 }*/ 576 try { 577 sig.initVerify(pgpPub.getPublicKey(sig.getKeyID()), "BC"); 578 sig.update(sigtext.getBytes(Charset.forName("UTF-8"))); 579 return sig.verify(); 580 }catch (Exception e){//Catch exception if any 581 System.err.println("PGP Verification Error: " + e.getMessage()); 582 } 583 return false; 584 } 585 586 587 // public static void writeSignatureToFile(PGPSignature sig, String clearText, FileOutputStream fout) throws Exception { 588 // ArmoredOutputStream aOut = new ArmoredOutputStream(fout); 589 // aOut.beginClearText(digest); 590 // aOut.write(clearText.getBytes(Charset.forName("UTF-8"))); 591 // aOut.write('\n'); 592 // aOut.endClearText(); 593 // 594 // BCPGOutputStream bOut = new BCPGOutputStream(aOut); 595 // sig.encode(bOut); 596 // aOut.close(); 597 // bOut.close(); 598 // } 599 // 600 // public Map<String, String> getKeyValueFromSignature(PGPSignature sig) { 601 // Map<String, String> tags = new HashMap<String, String>(); 602 // try { 603 // String sigtext = new String(sig.getEncoded(), Charset.forName("UTF-8")); 604 // String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(sigtext); 605 // tags.put(kv[0],kv[1]); 606 // } catch (IOException e) { 607 // // TODO Auto-generated catch block 608 // e.printStackTrace(); 609 // } 610 // return tags; 611 // } 612 613 public static void showKeyDetails(PGPPublicKey key) { 614 String userid = "Unknown"; 615 Iterator iter = key.getUserIDs(); 616 if (iter.hasNext()) { 617 userid = (String)iter.next(); 618 } 619 620 String fingerprint = new String(Hex.encode(key.getFingerprint())).toUpperCase(); 621 String keyid = "0x"+Long.toHexString(key.getKeyID()).substring(8).toUpperCase(); 622 623 String algorithm = ""; 624 int algo = key.getAlgorithm(); 625 switch(algo) { 626 case PGPPublicKey.DIFFIE_HELLMAN: 627 algorithm = "Diffie Hellman (DH)"; break; 628 case PGPPublicKey.DSA: 629 algorithm = "Digital Signature Algorithm (DSA)"; break; 630 case PGPPublicKey.EC: 631 algorithm = "Elliptic Curve (EC)"; break; 632 case PGPPublicKey.ECDSA: 633 algorithm = "Elliptic Curve Digital Signature Algorithm (ECDSA)"; break; 634 case PGPPublicKey.ELGAMAL_ENCRYPT: 635 algorithm = "Elgamal encrypt-only"; break; 636 case PGPPublicKey.ELGAMAL_GENERAL: 637 algorithm = "Elgamal"; break; 638 case PGPPublicKey.RSA_ENCRYPT: 639 algorithm = "Rivest Shamir Adleman (RSA) encrypt-only"; break; 640 case PGPPublicKey.RSA_GENERAL: 641 algorithm = "Rivest Shamir Adleman (RSA)"; break; 642 case PGPPublicKey.RSA_SIGN: 643 algorithm = "Rivest Shamir Adleman (RSA) sign-only"; break; 644 default: 645 algorithm = "Unknown algorithm ID: "+algo; break; 646 } 647 648 String strength = String.valueOf(key.getBitStrength()); 649 650 //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss"); 651 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 652 String creationTime = formatter.format(key.getCreationTime()); 653 654 long validSeconds = key.getValidSeconds(); 655 String expirationTime; 656 if (validSeconds == 0) { 657 expirationTime = tr("never"); 658 } else { 659 expirationTime = formatter.format(new Date(key.getCreationTime().getTime()+validSeconds*1000)); 660 } 661 662 663 String[] labels = {tr("Primary user-ID: "), tr("Key-ID: "), tr("Fingerprint: "), tr("Algorithm: "), tr("Strength in bit: "), tr("Creation date: "), tr("Expiration date: ")}; 664 String[] values = {userid, keyid, fingerprint, algorithm, strength, creationTime, expirationTime}; 665 int numPairs = labels.length; 666 667 //Create and populate the panel. 668 JPanel p = new JPanel(new SpringLayout()); 669 for (int i = 0; i < numPairs; i++) { 670 JLabel l = new JLabel(labels[i], JLabel.TRAILING); 671 p.add(l); 672 JTextField textField = new JTextField(values[i]); 673 textField.setEditable(false); 674 l.setLabelFor(textField); 675 p.add(textField); 676 } 677 678 //Lay out the panel. 679 SpringUtilities.makeCompactGrid(p, 680 numPairs, 2, //rows, cols 681 6, 6, //initX, initY 682 6, 6); //xPad, yPad 683 684 685 // JPanel metaPanel = new JPanel(); 686 // metaPanel.setLayout(new BoxLayout(metaPanel, BoxLayout.PAGE_AXIS)); 687 // metaPanel.add(p); 688 // JScrollPane sp = new JScrollPane(new KeySignaturesDialog(key)); 689 // sp.setPreferredSize(new Dimension(0,200)); 690 // metaPanel.add(sp); 691 692 JOptionPane.showMessageDialog(Main.parent, p, tr("PGP-Key details"), JOptionPane.INFORMATION_MESSAGE); 693 } 694 695 696 public PGPSecretKey generateKey() throws NoSuchAlgorithmException, NoSuchProviderException, PGPException, FileNotFoundException, IOException { 697 698 JTextField userId = new JTextField(); 699 NameGenerator nameGen = new NameGenerator(Main.pref.getPluginsDirectory().getPath()+"/trustosm/resources/syllables.txt"); 700 userId.setText(nameGen.compose(3)); 701 702 final String[] sizes = {"1024", "2048", "3072", "4096"}; 703 704 final JComboBox strengthBox = new JComboBox(sizes); 705 strengthBox.setEnabled(false); 706 707 /* final String[] curves = {"prime192v1", "prime192v2", "prime192v3", "prime239v1", "prime239v2", "prime239v3", "prime256v1", "secp224r1", "secp256r1", "secp384r1", "secp521r1", "P-224", "P-256", "P-384", "P-521", "c2pnb163v1", "c2pnb163v2", "c2pnb163v3", "c2pnb176w1", "c2tnb191v2", "c2tnb191v1", "c2tnb191v3", "c2pnb208w1", "c2tnb239v1", "c2tnb239v2", "c2tnb239v3", "c2pnb272w1", "c2pnb304w1", "c2tnb359v1", "c2pnb368w1", "c2tnb431r1", "sect163r2", "sect233r1", "sect283r1", "sect409r1", "sect571r1", "B-163", "B-233", "B-283", "B-409", "B-571", "brainpoolp160r1", "brainpoolp160t1", "brainpoolp192r1", "brainpoolp192t1", "brainpoolp224r1", "brainpoolp224t1", "brainpoolp256r1", "brainpoolp256t1", "brainpoolp320r1", "brainpoolp320t1", "brainpoolp384r1", "brainpoolp384t1", "brainpoolp512r1", "brainpoolp512t1"}; 708 final String[] curvesizes = {"192", "192", "192", "239", "239", "239", "256", "224", "256", "384", "521", "224", "256", "384", "521", "163", "163", "163", "176", "191", "191", "191", "208", "239", "239", "239", "272", "304", "359", "368", "431", "163", "233", "283", "409", "571", "163", "233", "283", "409", "571", "160", "160", "192", "192", "224", "224", "256", "256", "320", "320", "384", "384", "512", "512"}; 709 final JComboBox curveBox = new JComboBox(curves); 710 curveBox.addActionListener(new ActionListener(){ 711 712 @Override 713 public void actionPerformed(ActionEvent e) { 714 strengthBox.setSelectedIndex(((JComboBox)e.getSource()).getSelectedIndex()); 715 }}); 716 curveBox.setEnabled(false); 717 */ 718 719 // final String[] algos = {"DSA","RSA","ECDSA"}; 720 final String[] algos = {"DSA","RSA"}; 721 final JComboBox algoBox = new JComboBox(algos); 722 algoBox.addActionListener(new ActionListener(){ 723 724 @Override 725 public void actionPerformed(ActionEvent e) { 726 JComboBox cb = (JComboBox)e.getSource(); 727 String alg = (String)cb.getSelectedItem(); 728 if (alg.equals("DSA")) { 729 strengthBox.setSelectedItem("1024"); 730 strengthBox.setEnabled(false); 731 } else 732 strengthBox.setEnabled(true); 733 /*if (alg.equals("ECDSA")) { 734 curveBox.setEnabled(true); 735 strengthBox.setModel(new DefaultComboBoxModel(curvesizes)); 736 strengthBox.setSelectedItem(curvesizes[curveBox.getSelectedIndex()]); 737 strengthBox.setEnabled(false); 738 } else { 739 curveBox.setEnabled(false); 740 strengthBox.setModel(new DefaultComboBoxModel(sizes)); 741 strengthBox.setEnabled(true); 742 }*/ 743 } 744 }); 745 746 747 748 749 750 final String[] protectAlgos = {"AES_256", "AES_192", "AES_128", "BLOWFISH", "CAST5", "DES", "IDEA", "SAFER", "TRIPLE_DES", "TWOFISH", "NULL"}; 751 int[] protAl = {PGPEncryptedData.AES_256, PGPEncryptedData.AES_192, PGPEncryptedData.AES_128, PGPEncryptedData.BLOWFISH, PGPEncryptedData.CAST5, PGPEncryptedData.DES, PGPEncryptedData.IDEA, PGPEncryptedData.SAFER, PGPEncryptedData.TRIPLE_DES, PGPEncryptedData.TWOFISH, PGPEncryptedData.NULL}; 752 final JComboBox protectBox = new JComboBox(protectAlgos); 753 754 final JDateChooser cal = new JDateChooser(null, null, null, new JSpinnerDateEditor()); 755 cal.setPreferredSize(new Dimension(130,cal.getPreferredSize().height)); 756 757 final String[] labels = {tr("User-ID:"), tr("Select algorithm:"), tr("Choose Bitlength (Strength):"), tr("Encryption algorithm to protect private key:"), tr("Choose an expiry date for the key:")}; 758 final JComponent[] values = {userId, algoBox, strengthBox, protectBox, cal}; 759 760 int numPairs = labels.length; 761 762 //Create and populate the panel. 763 JPanel p = new JPanel(new SpringLayout()); 764 for (int i = 0; i < numPairs; i++) { 765 JLabel l = new JLabel(labels[i], JLabel.TRAILING); 766 p.add(l); 767 l.setLabelFor(values[i]); 768 p.add(values[i]); 769 } 770 771 //Lay out the panel. 772 SpringUtilities.makeCompactGrid(p, 773 numPairs, 2, //rows, cols 774 6, 6, //initX, initY 775 16, 6); //xPad, yPad 776 777 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Create a new signing key"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 778 779 if (n != JOptionPane.OK_OPTION) 780 return null; 781 782 783 String algo = (String)algoBox.getSelectedItem(); 784 785 KeyPairGenerator Kpg = KeyPairGenerator.getInstance(algo, "BC"); 786 787 int al; 788 /* if (algo.equals("ECDSA")) { 789 al = PGPPublicKey.ECDSA; 790 ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec((String)curveBox.getSelectedItem()); 791 try { 792 Kpg.initialize(ecSpec); 793 } catch (InvalidAlgorithmParameterException e1) { 794 // TODO Auto-generated catch block 795 System.err.println("EC-Parameter not accepted"); 796 e1.printStackTrace(); 797 } 798 } 799 else {*/ 800 Kpg.initialize(Integer.parseInt((String)strengthBox.getSelectedItem())); 801 // 802 // this takes a while as the key generator has to generate some DSA params 803 // before it generates the key. 804 // 805 806 if (algo.equals("RSA")) al = PGPPublicKey.RSA_GENERAL; 807 else al = PGPPublicKey.DSA; 808 // } 809 810 811 KeyPair kp = Kpg.generateKeyPair(); 812 813 Date now = new Date(); 814 PGPKeyPair pgpKp = new PGPKeyPair(al, kp, now); 815 816 getPasswordfromUser(); 817 818 PGPSignatureSubpacketVector subPck = null; 819 PGPSignatureSubpacketGenerator spGen = null; 820 Date expire = cal.getDate(); 821 if (expire != null && expire.after(now)) { 822 spGen = new PGPSignatureSubpacketGenerator(); 823 spGen.setKeyExpirationTime(true, (expire.getTime()-now.getTime())/1000); 824 subPck = spGen.generate(); 825 } 826 827 PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, pgpKp, 828 userId.getText(), protAl[protectBox.getSelectedIndex()], password, true, subPck, null, new SecureRandom(), "BC"); 829 830 if (pgpPub == null) { 831 Vector<PGPPublicKeyRing> pubKeyRing = new Vector<PGPPublicKeyRing>(1); 832 pubKeyRing.add(keyRingGen.generatePublicKeyRing()); 833 pgpPub = new PGPPublicKeyRingCollection(pubKeyRing); 834 } else { 835 pgpPub = PGPPublicKeyRingCollection.addPublicKeyRing(pgpPub, keyRingGen.generatePublicKeyRing()); 836 } 837 838 PGPSecretKeyRing secRing = keyRingGen.generateSecretKeyRing(); 839 if (pgpSec == null) { 840 Vector<PGPSecretKeyRing> secKeyRing = new Vector<PGPSecretKeyRing>(1); 841 secKeyRing.add(secRing); 842 pgpSec = new PGPSecretKeyRingCollection(secKeyRing); 843 } else { 844 pgpSec = PGPSecretKeyRingCollection.addSecretKeyRing(pgpSec, secRing); 845 } 846 847 848 writeGpgFiles(); 849 850 return secRing.getSecretKey(); 851 } 83 // private GnuPG gpg; 84 private char[] password; 85 private PGPSecretKeyRingCollection pgpSec; 86 private PGPPublicKeyRingCollection pgpPub; 87 private static int digest = PGPUtil.SHA1; 88 private PGPSecretKey pgpSecKey; 89 public boolean keepkey = false; 90 91 public static final String NOTATION_DATA_KEY = "trustosm@openstreetmap.org"; 92 93 public TrustGPG() { 94 Security.addProvider(new BouncyCastleProvider()); 95 try { 96 readGpgFiles(); 97 } catch (Exception e) { 98 // TODO Auto-generated catch block 99 e.printStackTrace(); 100 } 101 } 102 103 public PGPPublicKey getPublicKeyFromRing(long keyID) { 104 try { 105 if (pgpPub.contains(keyID)) 106 return pgpPub.getPublicKey(keyID); 107 else if (pgpSec.contains(keyID)) 108 return pgpSec.getSecretKey(keyID).getPublicKey(); 109 } catch (PGPException e) { 110 System.err.println("Could not read a PGPPublic key from your KeyRingCollectionFile. Stacktrace:"); 111 e.printStackTrace(); 112 } 113 return null; 114 } 115 116 public static String secKeytoString(PGPSecretKey k) { 117 String keyText = "0x"+Long.toHexString(k.getKeyID()).substring(8).toUpperCase() + " "; 118 // keyText = new String(Hex.encode(sigKey.getPublicKey().getFingerprint()),"UTF-8") + " "; 119 Iterator<?> iter = k.getUserIDs(); 120 if (iter.hasNext()) { 121 keyText += (String)iter.next(); 122 } 123 /* iter = sigKey.getUserIDs(); 124 while (iter.hasNext()) { 125 keyText += (String)iter.next() + "; "; 126 } 127 */ 128 return keyText.trim(); 129 } 130 131 private void readSecretKey() { 132 133 // if there is no KeyRingCollection we have to create a new one 134 if (pgpSec == null) { 135 try { 136 generateKey(); 137 } catch (Exception e) { 138 System.err.println("GPG Key Ring File could not be created in: "+Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 139 } 140 } 141 // 142 // we just loop through the collection till we find a key suitable for encryption, in the real 143 // world you would probably want to be a bit smarter about this. 144 // 145 if (keepkey) return; 146 147 final ArrayList<PGPSecretKey> sigKeys = new ArrayList<>(); 148 149 // 150 // iterate through the key rings. 151 // 152 Iterator<?> rIt = pgpSec.getKeyRings(); 153 154 while (rIt.hasNext()) { 155 156 PGPSecretKeyRing kRing = (PGPSecretKeyRing)rIt.next(); 157 Iterator<?> kIt = kRing.getSecretKeys(); 158 159 while (kIt.hasNext()) { 160 PGPSecretKey k = (PGPSecretKey)kIt.next(); 161 162 if (k.isSigningKey()) { 163 sigKeys.add(k); 164 } 165 } 166 } 167 168 169 Iterator<PGPSecretKey> skIt = sigKeys.iterator(); 170 171 final Vector<String> keys = new Vector<>(); 172 173 while (skIt.hasNext()) { 174 PGPSecretKey sigKey = skIt.next(); 175 keys.add(secKeytoString(sigKey)); 176 } 177 178 JPanel p = new JPanel(); 179 p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS)); 180 Dimension d = new Dimension(0,20); 181 182 JLabel head = new JLabel(tr("Select a signing key from your keyring-file:")); 183 head.setAlignmentX(Component.LEFT_ALIGNMENT); 184 p.add(head); 185 186 final JComboBox<String> keyBox = new JComboBox<>(keys); 187 keyBox.setAlignmentX(Component.LEFT_ALIGNMENT); 188 p.add(keyBox); 189 190 JCheckBox keepkeyBox = new JCheckBox(tr("Don''t ask again for the key")); 191 keepkeyBox.setAlignmentX(Component.LEFT_ALIGNMENT); 192 p.add(keepkeyBox); 193 194 JButton detailsButton = new JButton(tr("Details"), ImageProvider.get("keydetails")); 195 detailsButton.setAlignmentX(Component.LEFT_ALIGNMENT); 196 detailsButton.addActionListener(new ActionListener(){ 197 198 @Override 199 public void actionPerformed(ActionEvent arg0) { 200 PGPSecretKey sk = sigKeys.get(keyBox.getSelectedIndex()); 201 showKeyDetails(getPublicKeyFromRing(sk.getKeyID())); 202 }}); 203 p.add(detailsButton); 204 205 JCheckBox random = new JCheckBox(tr("Use a random key from this list")); 206 random.setAlignmentX(Component.LEFT_ALIGNMENT); 207 p.add(random); 208 209 p.add(Box.createRigidArea(d)); 210 211 JButton createButton = new JButton(tr("Create new Key"), ImageProvider.get("key")); 212 createButton.setAlignmentX(Component.LEFT_ALIGNMENT); 213 createButton.addActionListener(new ActionListener(){ 214 215 @Override 216 public void actionPerformed(ActionEvent arg0) { 217 try { 218 PGPSecretKey secKey = generateKey(); 219 if (secKey != null) { 220 keyBox.addItem(secKeytoString(secKey)); 221 sigKeys.add(secKey); 222 } 223 } catch (NoSuchAlgorithmException e) { 224 // TODO Auto-generated catch block 225 e.printStackTrace(); 226 } catch (NoSuchProviderException e) { 227 // TODO Auto-generated catch block 228 e.printStackTrace(); 229 } catch (FileNotFoundException e) { 230 // TODO Auto-generated catch block 231 e.printStackTrace(); 232 } catch (PGPException e) { 233 // TODO Auto-generated catch block 234 e.printStackTrace(); 235 } catch (IOException e) { 236 // TODO Auto-generated catch block 237 e.printStackTrace(); 238 } 239 240 }}); 241 p.add(createButton); 242 p.add(Box.createRigidArea(d)); 243 244 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Select a Key to sign"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, ImageProvider.get("keyring"), null, null); 245 246 if (n == JOptionPane.OK_OPTION) { 247 keepkey = keepkeyBox.isSelected(); 248 if (random.isSelected()) { 249 Random r = new Random(); 250 pgpSecKey = sigKeys.get(r.nextInt(sigKeys.size()-1)); 251 } else { 252 pgpSecKey = sigKeys.get(keyBox.getSelectedIndex()); 253 } 254 } else { 255 pgpSecKey = null; 256 } 257 //String selection = (String) JOptionPane.showInputDialog(null, tr("Select a Key to sign"),tr("Secret Key Choice"), JOptionPane.OK_CANCEL_OPTION, null, keys, keys[0]); 258 259 //System.out.println(selection); 260 261 // return pgpSecKey; 262 } 263 264 public void readGpgFiles() throws PGPException, IOException, NoSuchAlgorithmException, NoSuchProviderException { 265 FileInputStream pubIn; 266 FileInputStream secIn; 267 try { 268 pubIn = new FileInputStream(Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 269 secIn = new FileInputStream(Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/pubring.gpg"); 270 //pubIn = new FileInputStream("/tmp/secring.gpg"); 271 //secIn = new FileInputStream("/tmp/pubring.gpg"); 272 pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(pubIn)); 273 pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(secIn)); 274 } catch (FileNotFoundException e) { 275 System.err.println("No gpg files found in "+Main.pref.getPluginsDirectory().getPath() + "/trustosm/gnupg/secring.gpg"); 276 pgpSec = null; 277 pgpPub = null; 278 } 279 280 } 281 282 public void writeGpgFiles() throws FileNotFoundException, IOException { 283 String path = Main.pref.getPluginsDirectory().getPath(); 284 try (FileOutputStream pubOut = new FileOutputStream(path + "/trustosm/gnupg/pubring.gpg"); 285 FileOutputStream secOut = new FileOutputStream(path + "/trustosm/gnupg/secring.gpg")) { 286 pgpSec.encode(secOut); 287 pgpPub.encode(pubOut); 288 pubOut.flush(); 289 secOut.flush(); 290 } 291 } 292 293 public void getPasswordfromUser() { 294 295 final JPasswordField passwordField = new JPasswordField(); 296 JOptionPane jop = new JOptionPane(passwordField, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, ImageProvider.get("lock")); 297 JDialog dialog = jop.createDialog("Password:"); 298 dialog.addComponentListener(new ComponentAdapter(){ 299 @Override 300 public void componentShown(ComponentEvent e){ 301 passwordField.requestFocusInWindow(); 302 } 303 }); 304 dialog.setVisible(true); 305 int result = (Integer)jop.getValue(); 306 dialog.dispose(); 307 if(result == JOptionPane.OK_OPTION){ 308 password = passwordField.getPassword(); 309 } 310 311 312 /*final JPasswordField passwordField = new JPasswordField(10); 313 JOptionPane.showMessageDialog(Main.parent, passwordField, "Enter password", JOptionPane.OK_OPTION, ImageProvider.get("lock")); 314 password = passwordField.getPassword(); 315 */ 316 } 317 /* 318 public void checkTag(TrustOsmPrimitive trust, String key) { 319 String sigtext = TrustOsmPrimitive.generateTagSigtext(trust.getOsmPrimitive(),key); 320 TrustSignatures sigs; 321 if ((sigs = trust.getSigsOnKey(key))!=null) 322 for (PGPSignature sig : sigs.getSignatures()) { 323 trust.updateTagSigStatus(key, verify(sigtext,sig)? TrustSignatures.SIG_VALID : TrustSignatures.SIG_BROKEN); 324 } 325 } 326 327 328 329 /* public void checkAll(TrustOsmPrimitive trust) { 330 OsmPrimitive osm = trust.getOsmPrimitive(); 331 for (String key : osm.keySet()) { 332 checkTag(trust, key); 333 } 334 335 if(osm instanceof Node) { 336 checkNode((TrustNode) trust); 337 } else if(osm instanceof Way) { 338 /* Iterator<Node> iter = ((Way)osm).getNodes().iterator(); 339 while (iter.hasNext()) { 340 checkNode(trust, iter.next()); 341 }/ 342 } else if(osm instanceof Relation) { 343 344 } 345 } 346 */ 347 348 public void invalidIDWarning(OsmPrimitive osm) { 349 JOptionPane.showMessageDialog(Main.parent, tr("The object with the ID \"{0}\" ({1}) is newly created.\nYou can not sign it, because the signature would lose the ID-Reference after uploading it to the OSM-server.",osm.getUniqueId(),osm.toString()), tr("Signing canceled!"), JOptionPane.ERROR_MESSAGE); 350 } 351 /* 352 public TrustOsmPrimitive signGeometry(TrustOsmPrimitive trust) { 353 PGPSignatureSubpacketGenerator spGen = chooseAccuracy(); 354 PGPSignature s; 355 Node node; 356 OsmPrimitive osm = trust.getOsmPrimitive(); 357 if (osm.isNew()) { 358 invalidIDWarning(osm); 359 return trust; 360 } 361 if(osm instanceof Node) { 362 s = signNode(osm,(Node)osm, spGen); 363 if (s != null) ((TrustNode)trust).storeNodeSig(s); 364 } else if(osm instanceof Way) { 365 Iterator<Node> iter = ((Way)osm).getNodes().iterator(); 366 while (iter.hasNext()) { 367 node = iter.next(); 368 s = signNode(osm,node,spGen); 369 if (s != null) ((TrustNode)trust).storeNodeSig(s); 370 } 371 } else if(osm instanceof Relation) { 372 373 } 374 return trust; 375 }*/ 376 377 public TrustWay signWay(TrustWay trust) { 378 PGPSignature s; 379 Way w = (Way) trust.getOsmPrimitive(); 380 if (w.isNew()) { 381 invalidIDWarning(w); 382 return trust; 383 } 384 /* 385 List<Node> nodes = w.getNodes(); 386 s = signSegment(trust,nodes); 387 if (s != null) trust.storeSegmentSig(nodes,s); 388 */ 389 List<Node> wayNodes = w.getNodes(); 390 for (int i=0; i<wayNodes.size()-1; i++) { 391 List<Node> nodes = new ArrayList<>(); 392 nodes.add(wayNodes.get(i)); 393 nodes.add(wayNodes.get(i+1)); 394 s = signSegment(trust,nodes); 395 if (s != null) trust.storeSegmentSig(nodes,s); 396 } 397 398 return trust; 399 } 400 401 public PGPSignature signSegment(TrustWay trust, List<Node> nodes) { 402 Way w = (Way) trust.getOsmPrimitive(); 403 if (w.isNew()) { 404 invalidIDWarning(w); 405 return null; 406 } 407 String tosign = TrustWay.generateSegmentSigtext(trust,nodes); 408 PGPSignatureSubpacketGenerator spGen = chooseAccuracy(); 409 return sign(tosign,spGen); 410 } 411 412 public PGPSignature signNode(Node node) { 413 PGPSignatureSubpacketGenerator spGen = chooseAccuracy(); 414 return signNode(node,spGen); 415 } 416 417 public PGPSignature signNode(Node node, PGPSignatureSubpacketGenerator spGen) { 418 if (node.isNew()) { 419 invalidIDWarning(node); 420 return null; 421 } 422 String tosign = TrustNode.generateNodeSigtext(node); 423 return sign(tosign,spGen); 424 } 425 426 public boolean signTag(TrustOsmPrimitive trust, String key) { 427 OsmPrimitive osm = trust.getOsmPrimitive(); 428 if (osm.isNew()) { 429 invalidIDWarning(osm); 430 return false; 431 } 432 PGPSignature s; 433 String tosign = TrustOsmPrimitive.generateTagSigtext(osm,key); 434 //s = sign(tosign); 435 s = sign(tosign,chooseInformationSource()); 436 if (s != null) { 437 trust.storeTagSig(key, s); 438 return true; 439 } 440 return false; 441 } 442 443 /** 444 * Search in a given Signature for Tolerance information. 445 * @param sig 446 * @return found tolerance as double or 0 if no Tolerance is given 447 */ 448 449 public static double searchTolerance(PGPSignature sig) { 450 /** Take the first NotationData packet that seems to have Tolerance information */ 451 for (NotationData nd : sig.getHashedSubPackets().getNotationDataOccurences()){ 452 if (nd.getNotationName().equals(TrustGPG.NOTATION_DATA_KEY)) { 453 String notation = nd.getNotationValue(); 454 Pattern p = Pattern.compile("^Tolerance:(\\d*\\.?\\d*)m"); 455 Matcher m = p.matcher(notation); 456 if (m.matches()) { // we found a valid Tolerance 457 return Double.parseDouble(m.group(1)); 458 } 459 } 460 } 461 return 0; 462 } 463 464 public PGPSignatureSubpacketGenerator chooseAccuracy() { 465 PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); 466 JPanel p = new JPanel(new GridBagLayout()); 467 p.add(new JLabel(tr("Please give a tolerance in meters")),GBC.eol()); 468 469 JFormattedTextField meters = new JFormattedTextField(NumberFormat.getNumberInstance()); 470 meters.setValue(new Double(10)); 471 meters.setColumns(5); 472 473 p.add(meters,GBC.std()); 474 p.add(new JLabel(tr("meters")),GBC.eol()); 475 476 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Accuracy"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 477 478 if (n == JOptionPane.OK_OPTION) { 479 spGen.setNotationData(false, true, TrustGPG.NOTATION_DATA_KEY, "Tolerance:"+meters.getValue()+"m"); 480 return spGen; 481 } 482 return null; 483 } 484 485 public PGPSignatureSubpacketGenerator chooseInformationSource() { 486 PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); 487 JPanel p = new JPanel(new GridBagLayout()); 488 p.add(new JLabel(tr("Select as much as you like:")),GBC.eol()); 489 490 JCheckBox survey = new JCheckBox(tr("Survey")); 491 p.add(survey,GBC.eol()); 492 493 JCheckBox aerial = new JCheckBox(tr("Aerial Photography")); 494 p.add(aerial,GBC.eol()); 495 496 JCheckBox web = new JCheckBox(tr("Web Recherche")); 497 p.add(web,GBC.eol()); 498 499 JCheckBox trusted = new JCheckBox(tr("Trusted persons told me")); 500 p.add(trusted,GBC.eol()); 501 502 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Which source did you use?"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 503 504 if (n == JOptionPane.OK_OPTION) { 505 String sources = "Sources:"; 506 if (survey.isSelected()) sources += ":survey"; 507 if (aerial.isSelected()) sources += ":aerial"; 508 if (web.isSelected()) sources += ":web"; 509 if (trusted.isSelected()) sources += ":trusted"; 510 spGen.setNotationData(false, true, TrustGPG.NOTATION_DATA_KEY, sources); 511 return spGen; 512 } 513 return null; 514 } 515 516 public PGPSignature sign(String tosign) { 517 PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); 518 return sign(tosign,spGen); 519 } 520 521 public PGPSignature sign(String tosign, PGPSignatureSubpacketGenerator spGen) { 522 523 if (spGen == null) return null; 524 PGPSignature sig; 525 try{ 526 527 readSecretKey(); 528 if (pgpSec == null) return null; 529 530 if (password == null) { 531 getPasswordfromUser(); 532 } 533 534 PGPPrivateKey pgpPrivKey = pgpSecKey.extractPrivateKey(password, "BC"); 535 PGPSignatureGenerator sGen = new PGPSignatureGenerator(pgpSecKey.getPublicKey().getAlgorithm(), digest, "BC"); 536 sGen.initSign(PGPSignature.CANONICAL_TEXT_DOCUMENT, pgpPrivKey); 537 538 Iterator<?> it = pgpSecKey.getPublicKey().getUserIDs(); 539 if (it.hasNext()) { 540 spGen.setSignerUserID(false, (String)it.next()); 541 } 542 sGen.setHashedSubpackets(spGen.generate()); 543 sGen.update(tosign.getBytes(Charset.forName("UTF-8"))); 544 sig = sGen.generate(); 545 //System.out.println(new String(sGen.generateOnePassVersion(false).getEncoded(),Charset.forName("UTF-8"))); 546 //writeSignatureToFile(sig, tosign, new FileOutputStream("/tmp/sigtest.asc")); 547 //sig.encode(new BCPGOutputStream(new ArmoredOutputStream(new FileOutputStream("/tmp/sigtest.asc")))); 548 return sig; 549 }catch (Exception e){//Catch exception if any 550 System.err.println("PGP Signing Error: " + e.getMessage()); 551 } 552 553 554 /* String seckeys = gpg.listSecretKeys()? gpg.getResult() : "GPG-ERROR: " + gpg.getErrorString(); 555 System.out.println("Die gelisteten keys sehen so aus:\n"+seckeys); 556 String[] keys = seckeys.split("\n"); 557 System.out.println("Das Array hat so viele einträge:"+keys.length); 558 if (keys.length <= 1) { 559 System.out.println("Auf auf zum lustigen generieren!"); 560 generateKey(); 561 } 562 System.out.println("Achtung die Errorausgabe sieht so aus:\n"+gpg.getErrorString()); 563 String sig = gpg.sign(tosign, password)? gpg.getResult() : "GPG-ERROR: " + gpg.getErrorString(); 564 */ 565 566 567 return null; 568 } 569 570 public boolean verify(String sigtext, PGPSignature sig) { 571 /* if (gpg.verifySignature(sig)) { 572 success = trust.updateSigStatus(key, gpg.getResult().equals(sigtext)? TrustSignatures.SIG_VALID : TrustSignatures.SIG_BROKEN); 573 }*/ 574 try { 575 sig.initVerify(pgpPub.getPublicKey(sig.getKeyID()), "BC"); 576 sig.update(sigtext.getBytes(Charset.forName("UTF-8"))); 577 return sig.verify(); 578 }catch (Exception e){//Catch exception if any 579 System.err.println("PGP Verification Error: " + e.getMessage()); 580 } 581 return false; 582 } 583 584 585 // public static void writeSignatureToFile(PGPSignature sig, String clearText, FileOutputStream fout) throws Exception { 586 // ArmoredOutputStream aOut = new ArmoredOutputStream(fout); 587 // aOut.beginClearText(digest); 588 // aOut.write(clearText.getBytes(Charset.forName("UTF-8"))); 589 // aOut.write('\n'); 590 // aOut.endClearText(); 591 // 592 // BCPGOutputStream bOut = new BCPGOutputStream(aOut); 593 // sig.encode(bOut); 594 // aOut.close(); 595 // bOut.close(); 596 // } 597 // 598 // public Map<String, String> getKeyValueFromSignature(PGPSignature sig) { 599 // Map<String, String> tags = new HashMap<String, String>(); 600 // try { 601 // String sigtext = new String(sig.getEncoded(), Charset.forName("UTF-8")); 602 // String[] kv = TrustOsmPrimitive.generateTagsFromSigtext(sigtext); 603 // tags.put(kv[0],kv[1]); 604 // } catch (IOException e) { 605 // // TODO Auto-generated catch block 606 // e.printStackTrace(); 607 // } 608 // return tags; 609 // } 610 611 public static void showKeyDetails(PGPPublicKey key) { 612 String userid = "Unknown"; 613 Iterator<?> iter = key.getUserIDs(); 614 if (iter.hasNext()) { 615 userid = (String)iter.next(); 616 } 617 618 String fingerprint = new String(Hex.encode(key.getFingerprint())).toUpperCase(); 619 String keyid = "0x"+Long.toHexString(key.getKeyID()).substring(8).toUpperCase(); 620 621 String algorithm = ""; 622 int algo = key.getAlgorithm(); 623 switch(algo) { 624 case PGPPublicKey.DIFFIE_HELLMAN: 625 algorithm = "Diffie Hellman (DH)"; break; 626 case PGPPublicKey.DSA: 627 algorithm = "Digital Signature Algorithm (DSA)"; break; 628 case PGPPublicKey.EC: 629 algorithm = "Elliptic Curve (EC)"; break; 630 case PGPPublicKey.ECDSA: 631 algorithm = "Elliptic Curve Digital Signature Algorithm (ECDSA)"; break; 632 case PGPPublicKey.ELGAMAL_ENCRYPT: 633 algorithm = "Elgamal encrypt-only"; break; 634 case PGPPublicKey.ELGAMAL_GENERAL: 635 algorithm = "Elgamal"; break; 636 case PGPPublicKey.RSA_ENCRYPT: 637 algorithm = "Rivest Shamir Adleman (RSA) encrypt-only"; break; 638 case PGPPublicKey.RSA_GENERAL: 639 algorithm = "Rivest Shamir Adleman (RSA)"; break; 640 case PGPPublicKey.RSA_SIGN: 641 algorithm = "Rivest Shamir Adleman (RSA) sign-only"; break; 642 default: 643 algorithm = "Unknown algorithm ID: "+algo; break; 644 } 645 646 String strength = String.valueOf(key.getBitStrength()); 647 648 //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh.mm.ss"); 649 SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 650 String creationTime = formatter.format(key.getCreationTime()); 651 652 long validSeconds = key.getValidSeconds(); 653 String expirationTime; 654 if (validSeconds == 0) { 655 expirationTime = tr("never"); 656 } else { 657 expirationTime = formatter.format(new Date(key.getCreationTime().getTime()+validSeconds*1000)); 658 } 659 660 661 String[] labels = {tr("Primary user-ID: "), tr("Key-ID: "), tr("Fingerprint: "), tr("Algorithm: "), tr("Strength in bit: "), tr("Creation date: "), tr("Expiration date: ")}; 662 String[] values = {userid, keyid, fingerprint, algorithm, strength, creationTime, expirationTime}; 663 int numPairs = labels.length; 664 665 //Create and populate the panel. 666 JPanel p = new JPanel(new SpringLayout()); 667 for (int i = 0; i < numPairs; i++) { 668 JLabel l = new JLabel(labels[i], JLabel.TRAILING); 669 p.add(l); 670 JTextField textField = new JTextField(values[i]); 671 textField.setEditable(false); 672 l.setLabelFor(textField); 673 p.add(textField); 674 } 675 676 //Lay out the panel. 677 SpringUtilities.makeCompactGrid(p, 678 numPairs, 2, //rows, cols 679 6, 6, //initX, initY 680 6, 6); //xPad, yPad 681 682 683 // JPanel metaPanel = new JPanel(); 684 // metaPanel.setLayout(new BoxLayout(metaPanel, BoxLayout.PAGE_AXIS)); 685 // metaPanel.add(p); 686 // JScrollPane sp = new JScrollPane(new KeySignaturesDialog(key)); 687 // sp.setPreferredSize(new Dimension(0,200)); 688 // metaPanel.add(sp); 689 690 JOptionPane.showMessageDialog(Main.parent, p, tr("PGP-Key details"), JOptionPane.INFORMATION_MESSAGE); 691 } 692 693 694 public PGPSecretKey generateKey() throws NoSuchAlgorithmException, NoSuchProviderException, PGPException, FileNotFoundException, IOException { 695 696 JTextField userId = new JTextField(); 697 NameGenerator nameGen = new NameGenerator(Main.pref.getPluginsDirectory().getPath()+"/trustosm/resources/syllables.txt"); 698 userId.setText(nameGen.compose(3)); 699 700 final String[] sizes = {"1024", "2048", "3072", "4096"}; 701 702 final JComboBox<?> strengthBox = new JComboBox<Object>(sizes); 703 strengthBox.setEnabled(false); 704 705 /* final String[] curves = {"prime192v1", "prime192v2", "prime192v3", "prime239v1", "prime239v2", "prime239v3", "prime256v1", "secp224r1", "secp256r1", "secp384r1", "secp521r1", "P-224", "P-256", "P-384", "P-521", "c2pnb163v1", "c2pnb163v2", "c2pnb163v3", "c2pnb176w1", "c2tnb191v2", "c2tnb191v1", "c2tnb191v3", "c2pnb208w1", "c2tnb239v1", "c2tnb239v2", "c2tnb239v3", "c2pnb272w1", "c2pnb304w1", "c2tnb359v1", "c2pnb368w1", "c2tnb431r1", "sect163r2", "sect233r1", "sect283r1", "sect409r1", "sect571r1", "B-163", "B-233", "B-283", "B-409", "B-571", "brainpoolp160r1", "brainpoolp160t1", "brainpoolp192r1", "brainpoolp192t1", "brainpoolp224r1", "brainpoolp224t1", "brainpoolp256r1", "brainpoolp256t1", "brainpoolp320r1", "brainpoolp320t1", "brainpoolp384r1", "brainpoolp384t1", "brainpoolp512r1", "brainpoolp512t1"}; 706 final String[] curvesizes = {"192", "192", "192", "239", "239", "239", "256", "224", "256", "384", "521", "224", "256", "384", "521", "163", "163", "163", "176", "191", "191", "191", "208", "239", "239", "239", "272", "304", "359", "368", "431", "163", "233", "283", "409", "571", "163", "233", "283", "409", "571", "160", "160", "192", "192", "224", "224", "256", "256", "320", "320", "384", "384", "512", "512"}; 707 final JComboBox curveBox = new JComboBox(curves); 708 curveBox.addActionListener(new ActionListener(){ 709 710 @Override 711 public void actionPerformed(ActionEvent e) { 712 strengthBox.setSelectedIndex(((JComboBox)e.getSource()).getSelectedIndex()); 713 }}); 714 curveBox.setEnabled(false); 715 */ 716 717 // final String[] algos = {"DSA","RSA","ECDSA"}; 718 final String[] algos = {"DSA","RSA"}; 719 final JComboBox<?> algoBox = new JComboBox<Object>(algos); 720 algoBox.addActionListener(new ActionListener(){ 721 722 @Override 723 public void actionPerformed(ActionEvent e) { 724 JComboBox<?> cb = (JComboBox<?>)e.getSource(); 725 String alg = (String)cb.getSelectedItem(); 726 if (alg.equals("DSA")) { 727 strengthBox.setSelectedItem("1024"); 728 strengthBox.setEnabled(false); 729 } else 730 strengthBox.setEnabled(true); 731 /*if (alg.equals("ECDSA")) { 732 curveBox.setEnabled(true); 733 strengthBox.setModel(new DefaultComboBoxModel(curvesizes)); 734 strengthBox.setSelectedItem(curvesizes[curveBox.getSelectedIndex()]); 735 strengthBox.setEnabled(false); 736 } else { 737 curveBox.setEnabled(false); 738 strengthBox.setModel(new DefaultComboBoxModel(sizes)); 739 strengthBox.setEnabled(true); 740 }*/ 741 } 742 }); 743 744 745 746 747 748 final String[] protectAlgos = {"AES_256", "AES_192", "AES_128", "BLOWFISH", "CAST5", "DES", "IDEA", "SAFER", "TRIPLE_DES", "TWOFISH", "NULL"}; 749 int[] protAl = {PGPEncryptedData.AES_256, PGPEncryptedData.AES_192, PGPEncryptedData.AES_128, PGPEncryptedData.BLOWFISH, PGPEncryptedData.CAST5, PGPEncryptedData.DES, PGPEncryptedData.IDEA, PGPEncryptedData.SAFER, PGPEncryptedData.TRIPLE_DES, PGPEncryptedData.TWOFISH, PGPEncryptedData.NULL}; 750 final JComboBox<?> protectBox = new JComboBox<Object>(protectAlgos); 751 752 final JDateChooser cal = new JDateChooser(null, null, null, new JSpinnerDateEditor()); 753 cal.setPreferredSize(new Dimension(130,cal.getPreferredSize().height)); 754 755 final String[] labels = {tr("User-ID:"), tr("Select algorithm:"), tr("Choose Bitlength (Strength):"), tr("Encryption algorithm to protect private key:"), tr("Choose an expiry date for the key:")}; 756 final JComponent[] values = {userId, algoBox, strengthBox, protectBox, cal}; 757 758 int numPairs = labels.length; 759 760 //Create and populate the panel. 761 JPanel p = new JPanel(new SpringLayout()); 762 for (int i = 0; i < numPairs; i++) { 763 JLabel l = new JLabel(labels[i], JLabel.TRAILING); 764 p.add(l); 765 l.setLabelFor(values[i]); 766 p.add(values[i]); 767 } 768 769 //Lay out the panel. 770 SpringUtilities.makeCompactGrid(p, 771 numPairs, 2, //rows, cols 772 6, 6, //initX, initY 773 16, 6); //xPad, yPad 774 775 int n = JOptionPane.showOptionDialog(Main.parent, p, tr("Create a new signing key"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); 776 777 if (n != JOptionPane.OK_OPTION) 778 return null; 779 780 781 String algo = (String)algoBox.getSelectedItem(); 782 783 KeyPairGenerator Kpg = KeyPairGenerator.getInstance(algo, "BC"); 784 785 int al; 786 /* if (algo.equals("ECDSA")) { 787 al = PGPPublicKey.ECDSA; 788 ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec((String)curveBox.getSelectedItem()); 789 try { 790 Kpg.initialize(ecSpec); 791 } catch (InvalidAlgorithmParameterException e1) { 792 // TODO Auto-generated catch block 793 System.err.println("EC-Parameter not accepted"); 794 e1.printStackTrace(); 795 } 796 } 797 else {*/ 798 Kpg.initialize(Integer.parseInt((String)strengthBox.getSelectedItem())); 799 // 800 // this takes a while as the key generator has to generate some DSA params 801 // before it generates the key. 802 // 803 804 if (algo.equals("RSA")) al = PGPPublicKey.RSA_GENERAL; 805 else al = PGPPublicKey.DSA; 806 // } 807 808 809 KeyPair kp = Kpg.generateKeyPair(); 810 811 Date now = new Date(); 812 PGPKeyPair pgpKp = new PGPKeyPair(al, kp, now); 813 814 getPasswordfromUser(); 815 816 PGPSignatureSubpacketVector subPck = null; 817 PGPSignatureSubpacketGenerator spGen = null; 818 Date expire = cal.getDate(); 819 if (expire != null && expire.after(now)) { 820 spGen = new PGPSignatureSubpacketGenerator(); 821 spGen.setKeyExpirationTime(true, (expire.getTime()-now.getTime())/1000); 822 subPck = spGen.generate(); 823 } 824 825 PGPKeyRingGenerator keyRingGen = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION, pgpKp, 826 userId.getText(), protAl[protectBox.getSelectedIndex()], password, true, subPck, null, new SecureRandom(), "BC"); 827 828 if (pgpPub == null) { 829 Vector<PGPPublicKeyRing> pubKeyRing = new Vector<>(1); 830 pubKeyRing.add(keyRingGen.generatePublicKeyRing()); 831 pgpPub = new PGPPublicKeyRingCollection(pubKeyRing); 832 } else { 833 pgpPub = PGPPublicKeyRingCollection.addPublicKeyRing(pgpPub, keyRingGen.generatePublicKeyRing()); 834 } 835 836 PGPSecretKeyRing secRing = keyRingGen.generateSecretKeyRing(); 837 if (pgpSec == null) { 838 Vector<PGPSecretKeyRing> secKeyRing = new Vector<>(1); 839 secKeyRing.add(secRing); 840 pgpSec = new PGPSecretKeyRingCollection(secKeyRing); 841 } else { 842 pgpSec = PGPSecretKeyRingCollection.addSecretKeyRing(pgpSec, secRing); 843 } 844 845 846 writeGpgFiles(); 847 848 return secRing.getSecretKey(); 849 } 852 850 853 851 } -
applications/editors/josm/plugins/trustosm/src/tools/NameGenerator.java
r24389 r30724 49 49 */ 50 50 public class NameGenerator { 51 ArrayList<String> pre = new ArrayList<String>();52 ArrayList<String> mid = new ArrayList<String>();53 ArrayList<String> sur = new ArrayList<String>();54 55 final private static char[] vocals = {'a', 'e', 'i', 'o', 'u', 'ä', 'ö', 'õ', 'ü', 'y'};56 final private static char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p','q', 'r', 's', 't', 'v', 'w', 'x', 'y'};57 58 private String fileName;59 60 /**61 * Create new random name generator object. refresh() is automatically called.62 * @param fileName insert file name, where syllables are located63 * @throws IOException64 */65 public NameGenerator(String fileName) throws IOException{66 this.fileName = fileName;67 refresh();68 }69 70 /**71 * Change the file. refresh() is automatically called during the process.72 * @param fileName insert the file name, where syllables are located.73 * @throws IOException74 */75 public void changeFile(String fileName) throws IOException{76 if(fileName == null) throw new IOException("File name cannot be null");77 this.fileName = fileName;78 refresh();79 }80 81 /**82 * Refresh names from file. No need to call that method, if you are not changing the file during the operation of program, as this method83 * is called every time file name is changed or new NameGenerator object created.84 * @throws IOException85 */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){115 return s.substring(0,1).toUpperCase().concat(s.substring(1));116 }117 118 private boolean containsConsFirst(ArrayList<String> array){119 for(String s: array){120 if(consonantFirst(s)) return true;121 }122 return false;123 }124 125 private boolean containsVocFirst(ArrayList<String> array){126 for(String s: array){127 if(vocalFirst(s)) return true;128 }129 return false;130 }131 132 private boolean allowCons(ArrayList<String> array){133 for(String s: array){134 if(hatesPreviousVocals(s) || hatesPreviousConsonants(s) == false) return true;135 }136 return false;137 }138 139 private boolean allowVocs(ArrayList<String> array){140 for(String s: array){141 if(hatesPreviousConsonants(s) || hatesPreviousVocals(s) == false) return true;142 }143 return false;144 }145 146 private boolean expectsVocal(String s){147 if(s.substring(1).contains("+v")) return true;148 else return false;149 }150 private boolean expectsConsonant(String s){151 if(s.substring(1).contains("+c")) return true;152 else return false;153 }154 private boolean hatesPreviousVocals(String s){155 if(s.substring(1).contains("-c")) return true;156 else return false;157 }158 private boolean hatesPreviousConsonants(String s){159 if(s.substring(1).contains("-v")) return true;160 else return false;161 }162 163 private String pureSyl(String s){164 s = s.trim();165 if(s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1);166 return s.split(" ")[0];167 }168 169 private boolean vocalFirst(String s){170 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(0)).toLowerCase()));171 }172 173 private boolean consonantFirst(String s){174 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(0)).toLowerCase()));175 }176 177 private boolean vocalLast(String s){178 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase()));179 }180 181 private boolean consonantLast(String s){182 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase()));183 }184 185 186 /**187 * Compose a new name.188 * @param syls The number of syllables used in name.189 * @return Returns composed name as a String190 * @throws RuntimeException when logical mistakes are detected inside chosen file, and program is unable to complete the name.191 */192 public String compose(int syls){193 if(syls > 2 && mid.size() == 0) throw new RuntimeException("You are trying to create a name with more than 3 parts, which requires middle parts, " +194 "which you have none in the file "+fileName+". You should add some. Every word, which doesn't have + or - for a prefix is counted as a middle part.");195 if(pre.size() == 0) throw new RuntimeException("You have no prefixes to start creating a name. add some and use \"-\" prefix, to identify it as a prefix for a name. (example: -asd)");196 if(sur.size() == 0) throw new RuntimeException("You have no suffixes to end a name. add some and use \"+\" prefix, to identify it as a suffix for a name. (example: +asd)");197 if(syls < 1) throw new RuntimeException("compose(int syls) can't have less than 1 syllable");198 int expecting = 0; // 1 for vocal, 2 for consonant199 int last = 0; // 1 for vocal, 2 for consonant200 String name;201 int a = (int)(Math.random() * pre.size());202 203 if(vocalLast(pureSyl(pre.get(a)))) last = 1;204 else last = 2;205 206 if(syls > 2){207 if(expectsVocal(pre.get(a))){208 expecting = 1;209 if(containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " +210 "but there is none. You should add one, or remove requirement for one.. ");211 }212 if(expectsConsonant(pre.get(a))){213 expecting = 2;214 if(containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " +215 "but there is none. You should add one, or remove requirement for one.. ");216 }217 }218 else{219 if(expectsVocal(pre.get(a))){220 expecting = 1;221 if(containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " +222 "but there is none. You should add one, or remove requirement for one.. ");223 }224 if(expectsConsonant(pre.get(a))){225 expecting = 2;226 if(containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " +227 "but there is none. You should add one, or remove requirement for one.. ");228 }229 }230 if(vocalLast(pureSyl(pre.get(a))) && allowVocs(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a vocal, " +231 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" +232 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all.");233 234 if(consonantLast(pureSyl(pre.get(a))) && allowCons(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a consonant, " +235 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" +236 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all.");237 238 int b[] = new int[syls];239 for(int i = 0; i<b.length-2; i++){240 241 do{242 b[i] = (int)(Math.random() * mid.size());243 //System.out.println("exp " +expecting+" vocalF:"+vocalFirst(mid.get(b[i]))+" syl: "+mid.get(b[i]));244 }245 while(expecting == 1 && vocalFirst(pureSyl(mid.get(b[i]))) == false || expecting == 2 && consonantFirst(pureSyl(mid.get(b[i]))) == false246 || last == 1 && hatesPreviousVocals(mid.get(b[i])) || last == 2 && hatesPreviousConsonants(mid.get(b[i])));247 248 expecting = 0;249 if(expectsVocal(mid.get(b[i]))){250 expecting = 1;251 if(i < b.length-3 && containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " +252 "but there is none. You should add one, or remove requirement for one.. ");253 if(i == b.length-3 && containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " +254 "but there is none. You should add one, or remove requirement for one.. ");255 }256 if(expectsConsonant(mid.get(b[i]))){257 expecting = 2;258 if(i < b.length-3 && containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " +259 "but there is none. You should add one, or remove requirement for one.. ");260 if(i == b.length-3 && containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " +261 "but there is none. You should add one, or remove requirement for one.. ");262 }263 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a vocal, " +264 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +265 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all.");266 267 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a consonant, " +268 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +269 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all.");270 if(i == b.length-3){271 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a vocal, " +272 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +273 "means there should be a suffix available, that has \"-v\" requirement or no requirements for previous syllables at all.");274 275 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a consonant, " +276 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +277 "means there should be a suffix available, that has \"-c\" requirement or no requirements for previous syllables at all.");278 }279 if(vocalLast(pureSyl(mid.get(b[i])))) last = 1;280 else last = 2;281 }282 283 int c;284 do{285 c = (int)(Math.random() * sur.size());286 }287 while(expecting == 1 && vocalFirst(pureSyl(sur.get(c))) == false || expecting == 2 && consonantFirst(pureSyl(sur.get(c))) == false288 || last == 1 && hatesPreviousVocals(sur.get(c)) || last == 2 && hatesPreviousConsonants(sur.get(c)));289 290 name = upper(pureSyl(pre.get(a).toLowerCase()));291 for(int i = 0; i<b.length-2; i++){292 name = name.concat(pureSyl(mid.get(b[i]).toLowerCase()));293 }294 if(syls > 1)295 name = name.concat(pureSyl(sur.get(c).toLowerCase()));296 return name;297 }51 ArrayList<String> pre = new ArrayList<String>(); 52 ArrayList<String> mid = new ArrayList<String>(); 53 ArrayList<String> sur = new ArrayList<String>(); 54 55 final private static char[] vocals = {'a', 'e', 'i', 'o', 'u', 'ä', 'ö', 'õ', 'ü', 'y'}; 56 final private static char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y'}; 57 58 private String fileName; 59 60 /** 61 * Create new random name generator object. refresh() is automatically called. 62 * @param fileName insert file name, where syllables are located 63 * @throws IOException 64 */ 65 public NameGenerator(String fileName) throws IOException{ 66 this.fileName = fileName; 67 refresh(); 68 } 69 70 /** 71 * Change the file. refresh() is automatically called during the process. 72 * @param fileName insert the file name, where syllables are located. 73 * @throws IOException 74 */ 75 public void changeFile(String fileName) throws IOException{ 76 if(fileName == null) throw new IOException("File name cannot be null"); 77 this.fileName = fileName; 78 refresh(); 79 } 80 81 /** 82 * Refresh names from file. No need to call that method, if you are not changing the file during the operation of program, as this method 83 * is called every time file name is changed or new NameGenerator object created. 84 * @throws IOException 85 */ 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){ 115 return s.substring(0,1).toUpperCase().concat(s.substring(1)); 116 } 117 118 private boolean containsConsFirst(ArrayList<String> array){ 119 for(String s: array){ 120 if(consonantFirst(s)) return true; 121 } 122 return false; 123 } 124 125 private boolean containsVocFirst(ArrayList<String> array){ 126 for(String s: array){ 127 if(vocalFirst(s)) return true; 128 } 129 return false; 130 } 131 132 private boolean allowCons(ArrayList<String> array){ 133 for(String s: array){ 134 if(hatesPreviousVocals(s) || hatesPreviousConsonants(s) == false) return true; 135 } 136 return false; 137 } 138 139 private boolean allowVocs(ArrayList<String> array){ 140 for(String s: array){ 141 if(hatesPreviousConsonants(s) || hatesPreviousVocals(s) == false) return true; 142 } 143 return false; 144 } 145 146 private boolean expectsVocal(String s){ 147 if(s.substring(1).contains("+v")) return true; 148 else return false; 149 } 150 private boolean expectsConsonant(String s){ 151 if(s.substring(1).contains("+c")) return true; 152 else return false; 153 } 154 private boolean hatesPreviousVocals(String s){ 155 if(s.substring(1).contains("-c")) return true; 156 else return false; 157 } 158 private boolean hatesPreviousConsonants(String s){ 159 if(s.substring(1).contains("-v")) return true; 160 else return false; 161 } 162 163 private String pureSyl(String s){ 164 s = s.trim(); 165 if(s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1); 166 return s.split(" ")[0]; 167 } 168 169 private boolean vocalFirst(String s){ 170 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(0)).toLowerCase())); 171 } 172 173 private boolean consonantFirst(String s){ 174 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(0)).toLowerCase())); 175 } 176 177 private boolean vocalLast(String s){ 178 return (String.copyValueOf(vocals).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase())); 179 } 180 181 private boolean consonantLast(String s){ 182 return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase())); 183 } 184 185 186 /** 187 * Compose a new name. 188 * @param syls The number of syllables used in name. 189 * @return Returns composed name as a String 190 * @throws RuntimeException when logical mistakes are detected inside chosen file, and program is unable to complete the name. 191 */ 192 public String compose(int syls){ 193 if(syls > 2 && mid.size() == 0) throw new RuntimeException("You are trying to create a name with more than 3 parts, which requires middle parts, " + 194 "which you have none in the file "+fileName+". You should add some. Every word, which doesn't have + or - for a prefix is counted as a middle part."); 195 if(pre.size() == 0) throw new RuntimeException("You have no prefixes to start creating a name. add some and use \"-\" prefix, to identify it as a prefix for a name. (example: -asd)"); 196 if(sur.size() == 0) throw new RuntimeException("You have no suffixes to end a name. add some and use \"+\" prefix, to identify it as a suffix for a name. (example: +asd)"); 197 if(syls < 1) throw new RuntimeException("compose(int syls) can't have less than 1 syllable"); 198 int expecting = 0; // 1 for vocal, 2 for consonant 199 int last = 0; // 1 for vocal, 2 for consonant 200 String name; 201 int a = (int)(Math.random() * pre.size()); 202 203 if(vocalLast(pureSyl(pre.get(a)))) last = 1; 204 else last = 2; 205 206 if(syls > 2){ 207 if(expectsVocal(pre.get(a))){ 208 expecting = 1; 209 if(containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " + 210 "but there is none. You should add one, or remove requirement for one.. "); 211 } 212 if(expectsConsonant(pre.get(a))){ 213 expecting = 2; 214 if(containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " + 215 "but there is none. You should add one, or remove requirement for one.. "); 216 } 217 } 218 else{ 219 if(expectsVocal(pre.get(a))){ 220 expecting = 1; 221 if(containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " + 222 "but there is none. You should add one, or remove requirement for one.. "); 223 } 224 if(expectsConsonant(pre.get(a))){ 225 expecting = 2; 226 if(containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " + 227 "but there is none. You should add one, or remove requirement for one.. "); 228 } 229 } 230 if(vocalLast(pureSyl(pre.get(a))) && allowVocs(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a vocal, " + 231 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" + 232 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all."); 233 234 if(consonantLast(pureSyl(pre.get(a))) && allowCons(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a consonant, " + 235 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" + 236 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all."); 237 238 int b[] = new int[syls]; 239 for(int i = 0; i<b.length-2; i++){ 240 241 do{ 242 b[i] = (int)(Math.random() * mid.size()); 243 //System.out.println("exp " +expecting+" vocalF:"+vocalFirst(mid.get(b[i]))+" syl: "+mid.get(b[i])); 244 } 245 while(expecting == 1 && vocalFirst(pureSyl(mid.get(b[i]))) == false || expecting == 2 && consonantFirst(pureSyl(mid.get(b[i]))) == false 246 || last == 1 && hatesPreviousVocals(mid.get(b[i])) || last == 2 && hatesPreviousConsonants(mid.get(b[i]))); 247 248 expecting = 0; 249 if(expectsVocal(mid.get(b[i]))){ 250 expecting = 1; 251 if(i < b.length-3 && containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with vocal, " + 252 "but there is none. You should add one, or remove requirement for one.. "); 253 if(i == b.length-3 && containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with vocal, " + 254 "but there is none. You should add one, or remove requirement for one.. "); 255 } 256 if(expectsConsonant(mid.get(b[i]))){ 257 expecting = 2; 258 if(i < b.length-3 && containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " + 259 "but there is none. You should add one, or remove requirement for one.. "); 260 if(i == b.length-3 && containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " + 261 "but there is none. You should add one, or remove requirement for one.. "); 262 } 263 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a vocal, " + 264 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 265 "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all."); 266 267 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a consonant, " + 268 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 269 "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all."); 270 if(i == b.length-3){ 271 if(vocalLast(pureSyl(mid.get(b[i]))) && allowVocs(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a vocal, " + 272 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 273 "means there should be a suffix available, that has \"-v\" requirement or no requirements for previous syllables at all."); 274 275 if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a consonant, " + 276 "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " + 277 "means there should be a suffix available, that has \"-c\" requirement or no requirements for previous syllables at all."); 278 } 279 if(vocalLast(pureSyl(mid.get(b[i])))) last = 1; 280 else last = 2; 281 } 282 283 int c; 284 do{ 285 c = (int)(Math.random() * sur.size()); 286 } 287 while(expecting == 1 && vocalFirst(pureSyl(sur.get(c))) == false || expecting == 2 && consonantFirst(pureSyl(sur.get(c))) == false 288 || last == 1 && hatesPreviousVocals(sur.get(c)) || last == 2 && hatesPreviousConsonants(sur.get(c))); 289 290 name = upper(pureSyl(pre.get(a).toLowerCase())); 291 for(int i = 0; i<b.length-2; i++){ 292 name = name.concat(pureSyl(mid.get(b[i]).toLowerCase())); 293 } 294 if(syls > 1) 295 name = name.concat(pureSyl(sur.get(c).toLowerCase())); 296 return name; 297 } 298 298 }
Note:
See TracChangeset
for help on using the changeset viewer.
