@Override public void visit(Way w) { if (!w.isUsable()) return; List<Node> wNodes = w.getNodes(); List<LatLon> wLat = new ArrayList<LatLon>(wNodes.size()); for (int i = 0; i < wNodes.size(); i++) { wLat.add(wNodes.get(i).getCoor()); } Map<String, String> wkeys = w.getKeys(); removeUninterestingKeys(wkeys); WayPair wKey = new WayPair(wLat, wkeys); ways.put(wKey, w); WayPairNoTags wKeyN = new WayPairNoTags(wLat); waysNoTags.put(wKeyN, w); }
/** Map a key to a value. Can be called multiple times with the same key, but different value. */ public void put(A key, B value) { LinkedHashSet<B> vals = get(key); if (vals == null) { vals = new LinkedHashSet<B>(); put(key, vals); } vals.add(value); }
@Override public void visit(Relation r) { if (!r.isUsable() || r.hasIncompleteMembers()) return; List<RelationMember> rMembers = r.getMembers(); Map<String, String> rkeys = r.getKeys(); for (String key : ignoreKeys) rkeys.remove(key); RelationPair rKey = new RelationPair(rMembers, rkeys); relations.put(rKey, r); relations_nokeys.put(rMembers, r); }
@Override public String getToolTipText() { MultiMap<Severity, TestError> errorTree = new MultiMap<Severity, TestError>(); List<TestError> errors = Main.map.validatorDialog.tree.getErrors(); for (TestError e : errors) { errorTree.put(e.getSeverity(), e); } StringBuilder b = new StringBuilder(); for (Severity s : Severity.values()) { if (errorTree.containsKey(s)) { b.append(tr(s.toString())).append(": ").append(errorTree.get(s).size()).append("<br>"); } } if (b.length() == 0) return "<html>" + tr("No validation errors") + "</html>"; else return "<html>" + tr("Validation errors") + ":<br>" + b + "</html>"; }
@Override protected void realRun() throws SAXException, IOException, OsmTransferException { if (files == null || files.isEmpty()) return; /** Find the importer with the chosen file filter */ FileImporter chosenImporter = null; for (FileImporter importer : ExtensionFileFilter.importers) { if (fileFilter == importer.filter) { chosenImporter = importer; } } /** * If the filter hasn't been changed in the dialog, chosenImporter is null now. When the * filter has been set explicitly to AllFormatsImporter, treat this the same. */ if (chosenImporter instanceof AllFormatsImporter) { chosenImporter = null; } getProgressMonitor().setTicksCount(files.size()); if (chosenImporter != null) { // The importer was explicitly chosen, so use it. List<File> filesNotMatchingWithImporter = new LinkedList<File>(); List<File> filesMatchingWithImporter = new LinkedList<File>(); for (final File f : files) { if (!chosenImporter.acceptFile(f)) { if (f.isDirectory()) { SwingUtilities.invokeLater( new Runnable() { @Override public void run() { JOptionPane.showMessageDialog( Main.parent, tr( "<html>Cannot open directory ''{0}''.<br>Please select a file.</html>", f.getAbsolutePath()), tr("Open file"), JOptionPane.ERROR_MESSAGE); } }); // TODO when changing to Java 6: Don't cancel the // task here but use different modality. (Currently 2 dialogs // would block each other.) return; } else { filesNotMatchingWithImporter.add(f); } } else { filesMatchingWithImporter.add(f); } } if (!filesNotMatchingWithImporter.isEmpty()) { alertFilesNotMatchingWithImporter(filesNotMatchingWithImporter, chosenImporter); } if (!filesMatchingWithImporter.isEmpty()) { importData(chosenImporter, filesMatchingWithImporter); } } else { // find appropriate importer MultiMap<FileImporter, File> importerMap = new MultiMap<FileImporter, File>(); List<File> filesWithUnknownImporter = new LinkedList<File>(); List<File> urlFiles = new LinkedList<File>(); FILES: for (File f : files) { for (FileImporter importer : ExtensionFileFilter.importers) { if (importer.acceptFile(f)) { importerMap.put(importer, f); continue FILES; } } if (urlFileFilter.accept(f)) { urlFiles.add(f); } else { filesWithUnknownImporter.add(f); } } if (!filesWithUnknownImporter.isEmpty()) { alertFilesWithUnknownImporter(filesWithUnknownImporter); } List<FileImporter> importers = new ArrayList<FileImporter>(importerMap.keySet()); Collections.sort(importers); Collections.reverse(importers); Set<String> fileHistory = new LinkedHashSet<String>(); Set<String> failedAll = new HashSet<String>(); for (FileImporter importer : importers) { List<File> files = new ArrayList<File>(importerMap.get(importer)); importData(importer, files); // suppose all files will fail to load List<File> failedFiles = new ArrayList<File>(files); if (recordHistory && !importer.isBatchImporter()) { // remove the files which didn't fail to load from the failed list failedFiles.removeAll(successfullyOpenedFiles); for (File f : successfullyOpenedFiles) { fileHistory.add(f.getCanonicalPath()); } for (File f : failedFiles) { failedAll.add(f.getCanonicalPath()); } } } for (File urlFile : urlFiles) { try { BufferedReader reader = new BufferedReader(new FileReader(urlFile)); String line; while ((line = reader.readLine()) != null) { Matcher m = Pattern.compile(".*(http://.*)").matcher(line); if (m.matches()) { String url = m.group(1); Main.main.menu.openLocation.openUrl(false, url); } } Utils.close(reader); } catch (Exception e) { Main.error(e); } } if (recordHistory) { Collection<String> oldFileHistory = Main.pref.getCollection("file-open.history"); fileHistory.addAll(oldFileHistory); // remove the files which failed to load from the list fileHistory.removeAll(failedAll); int maxsize = Math.max(0, Main.pref.getInteger("file-open.history.max-size", 15)); Main.pref.putCollectionBounded("file-open.history", maxsize, fileHistory); } } }
private void parseJos(Document doc, ProgressMonitor progressMonitor) throws IllegalDataException { Element root = doc.getDocumentElement(); if (!equal(root.getTagName(), "josm-session")) { error(tr("Unexpected root element ''{0}'' in session file", root.getTagName())); } String version = root.getAttribute("version"); if (!"0.1".equals(version)) { error(tr("Version ''{0}'' of session file is not supported. Expected: 0.1", version)); } Element viewportEl = getElementByTagName(root, "viewport"); if (viewportEl != null) { EastNorth center = null; Element centerEl = getElementByTagName(viewportEl, "center"); if (centerEl != null && centerEl.hasAttribute("lat") && centerEl.hasAttribute("lon")) { try { LatLon centerLL = new LatLon( Double.parseDouble(centerEl.getAttribute("lat")), Double.parseDouble(centerEl.getAttribute("lon"))); center = Projections.project(centerLL); } catch (NumberFormatException ex) { } } if (center != null) { Element scaleEl = getElementByTagName(viewportEl, "scale"); if (scaleEl != null && scaleEl.hasAttribute("meter-per-pixel")) { try { double meterPerPixel = Double.parseDouble(scaleEl.getAttribute("meter-per-pixel")); Projection proj = Main.getProjection(); // Get a "typical" distance in east/north units that // corresponds to a couple of pixels. Shouldn't be too // large, to keep it within projection bounds and // not too small to avoid rounding errors. double dist = 0.01 * proj.getDefaultZoomInPPD(); LatLon ll1 = proj.eastNorth2latlon(new EastNorth(center.east() - dist, center.north())); LatLon ll2 = proj.eastNorth2latlon(new EastNorth(center.east() + dist, center.north())); double meterPerEasting = ll1.greatCircleDistance(ll2) / dist / 2; double scale = meterPerPixel / meterPerEasting; // unit: easting per pixel viewport = new ViewportData(center, scale); } catch (NumberFormatException ex) { } } } } Element layersEl = getElementByTagName(root, "layers"); if (layersEl == null) return; String activeAtt = layersEl.getAttribute("active"); try { active = (activeAtt != null && !activeAtt.isEmpty()) ? Integer.parseInt(activeAtt) - 1 : -1; } catch (NumberFormatException e) { Main.warn( "Unsupported value for 'active' layer attribute. Ignoring it. Error was: " + e.getMessage()); active = -1; } MultiMap<Integer, Integer> deps = new MultiMap<Integer, Integer>(); Map<Integer, Element> elems = new HashMap<Integer, Element>(); NodeList nodes = layersEl.getChildNodes(); for (int i = 0; i < nodes.getLength(); ++i) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; if (equal(e.getTagName(), "layer")) { if (!e.hasAttribute("index")) { error(tr("missing mandatory attribute ''index'' for element ''layer''")); } Integer idx = null; try { idx = Integer.parseInt(e.getAttribute("index")); } catch (NumberFormatException ex) { } if (idx == null) { error(tr("unexpected format of attribute ''index'' for element ''layer''")); } if (elems.containsKey(idx)) { error( tr( "attribute ''index'' ({0}) for element ''layer'' must be unique", Integer.toString(idx))); } elems.put(idx, e); deps.putVoid(idx); String depStr = e.getAttribute("depends"); if (depStr != null) { for (String sd : depStr.split(",")) { Integer d = null; try { d = Integer.parseInt(sd); } catch (NumberFormatException ex) { Main.warn(ex); } if (d != null) { deps.put(idx, d); } } } } } } List<Integer> sorted = Utils.topologicalSort(deps); final Map<Integer, Layer> layersMap = new TreeMap<Integer, Layer>(Collections.reverseOrder()); final Map<Integer, SessionLayerImporter> importers = new HashMap<Integer, SessionLayerImporter>(); final Map<Integer, String> names = new HashMap<Integer, String>(); progressMonitor.setTicksCount(sorted.size()); LAYER: for (int idx : sorted) { Element e = elems.get(idx); if (e == null) { error(tr("missing layer with index {0}", idx)); } if (!e.hasAttribute("name")) { error(tr("missing mandatory attribute ''name'' for element ''layer''")); } String name = e.getAttribute("name"); names.put(idx, name); if (!e.hasAttribute("type")) { error(tr("missing mandatory attribute ''type'' for element ''layer''")); } String type = e.getAttribute("type"); SessionLayerImporter imp = getSessionLayerImporter(type); if (imp == null) { CancelOrContinueDialog dialog = new CancelOrContinueDialog(); dialog.show( tr("Unable to load layer"), tr("Cannot load layer of type ''{0}'' because no suitable importer was found.", type), JOptionPane.WARNING_MESSAGE, progressMonitor); if (dialog.isCancel()) { progressMonitor.cancel(); return; } else { continue; } } else { importers.put(idx, imp); List<LayerDependency> depsImp = new ArrayList<LayerDependency>(); for (int d : deps.get(idx)) { SessionLayerImporter dImp = importers.get(d); if (dImp == null) { CancelOrContinueDialog dialog = new CancelOrContinueDialog(); dialog.show( tr("Unable to load layer"), tr( "Cannot load layer {0} because it depends on layer {1} which has been skipped.", idx, d), JOptionPane.WARNING_MESSAGE, progressMonitor); if (dialog.isCancel()) { progressMonitor.cancel(); return; } else { continue LAYER; } } depsImp.add(new LayerDependency(d, layersMap.get(d), dImp)); } ImportSupport support = new ImportSupport(name, idx, depsImp); Layer layer = null; Exception exception = null; try { layer = imp.load(e, support, progressMonitor.createSubTaskMonitor(1, false)); } catch (IllegalDataException ex) { exception = ex; } catch (IOException ex) { exception = ex; } if (exception != null) { exception.printStackTrace(); CancelOrContinueDialog dialog = new CancelOrContinueDialog(); dialog.show( tr("Error loading layer"), tr( "<html>Could not load layer {0} ''{1}''.<br>Error is:<br>{2}</html>", idx, name, exception.getMessage()), JOptionPane.ERROR_MESSAGE, progressMonitor); if (dialog.isCancel()) { progressMonitor.cancel(); return; } else { continue; } } if (layer == null) throw new RuntimeException(); layersMap.put(idx, layer); } progressMonitor.worked(1); } layers = new ArrayList<Layer>(); for (int idx : layersMap.keySet()) { Layer layer = layersMap.get(idx); if (layer == null) { continue; } Element el = elems.get(idx); if (el.hasAttribute("visible")) { layer.setVisible(Boolean.parseBoolean(el.getAttribute("visible"))); } if (el.hasAttribute("opacity")) { try { double opacity = Double.parseDouble(el.getAttribute("opacity")); layer.setOpacity(opacity); } catch (NumberFormatException ex) { Main.warn(ex); } } } for (Entry<Integer, Layer> e : layersMap.entrySet()) { Layer l = e.getValue(); if (l == null) { continue; } l.setName(names.get(e.getKey())); layers.add(l); } }
/** Put a key that maps to nothing. */ public void putVoid(A key) { if (containsKey(key)) return; put(key, new LinkedHashSet<B>()); }