source: osm/applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/DownloadSVGBuilding.java@ 32202

Last change on this file since 32202 was 32060, checked in by donvip, 9 years ago

remove tabs

File size: 11.3 KB
Line 
1// License: GPL. v2 and later. Copyright 2008-2009 by Pieren <pieren3@gmail.com> and others
2package cadastre_fr;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedOutputStream;
7import java.io.BufferedReader;
8import java.io.File;
9import java.io.FileOutputStream;
10import java.io.IOException;
11import java.io.InputStream;
12import java.io.InputStreamReader;
13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
15import java.net.URL;
16import java.util.ArrayList;
17import java.util.Collection;
18import java.util.LinkedList;
19
20import javax.swing.JOptionPane;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.command.AddCommand;
24import org.openstreetmap.josm.command.Command;
25import org.openstreetmap.josm.command.SequenceCommand;
26import org.openstreetmap.josm.data.coor.EastNorth;
27import org.openstreetmap.josm.data.osm.DataSet;
28import org.openstreetmap.josm.data.osm.Node;
29import org.openstreetmap.josm.data.osm.Way;
30import org.openstreetmap.josm.gui.MapView;
31import org.openstreetmap.josm.gui.PleaseWaitRunnable;
32import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
33import org.openstreetmap.josm.io.OsmTransferException;
34import org.openstreetmap.josm.io.ProgressInputStream;
35
36public class DownloadSVGBuilding extends PleaseWaitRunnable {
37
38 private WMSLayer wmsLayer;
39 private CadastreInterface wmsInterface;
40 private String svg = null;
41 private static EastNorthBound currentView = null;
42 private EastNorthBound viewBox = null;
43 private static String errorMessage;
44
45 /**
46 * Constructs a new {@code DownloadSVGBuilding}.
47 */
48 public DownloadSVGBuilding(WMSLayer wmsLayer) {
49 super(tr("Downloading {0}", wmsLayer.getName()));
50
51 this.wmsLayer = wmsLayer;
52 this.wmsInterface = wmsLayer.grabber.getWmsInterface();
53 }
54
55 @Override
56 public void realRun() throws IOException, OsmTransferException {
57 progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
58 errorMessage = null;
59 try {
60 if (wmsInterface.retrieveInterface(wmsLayer)) {
61 svg = grabBoundary(currentView);
62 if (svg == null)
63 return;
64 getViewBox(svg);
65 if (viewBox == null)
66 return;
67 createBuildings(svg);
68 }
69 } catch (DuplicateLayerException e) {
70 Main.warn("removed a duplicated layer");
71 } catch (WMSException e) {
72 errorMessage = e.getMessage();
73 wmsLayer.grabber.getWmsInterface().resetCookie();
74 }
75 }
76
77 @Override
78 protected void cancel() {
79 wmsLayer.grabber.getWmsInterface().cancel();
80 }
81
82 @Override
83 protected void finish() {
84 }
85
86 private boolean getViewBox(String svg) {
87 double[] box = new SVGParser().getViewBox(svg);
88 if (box != null) {
89 viewBox = new EastNorthBound(new EastNorth(box[0], box[1]),
90 new EastNorth(box[0]+box[2], box[1]+box[3]));
91 return true;
92 }
93 Main.warn("Unable to parse SVG data (viewBox)");
94 return false;
95 }
96
97 /**
98 * The svg contains more than one commune boundary defined by path elements. So detect
99 * which path element is the best fitting to the viewBox and convert it to OSM objects
100 */
101 private void createBuildings(String svg) {
102 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
103 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<>();
104
105 // convert SVG nodes to eastNorth coordinates
106 for (int i=0; i< SVGpaths.length; i++) {
107 ArrayList<EastNorth> eastNorth = new ArrayList<>();
108 createNodes(SVGpaths[i], eastNorth);
109 if (eastNorth.size() > 2)
110 eastNorths.add(eastNorth);
111 }
112
113 // create nodes and closed ways
114 DataSet svgDataSet = new DataSet();
115 for (ArrayList<EastNorth> path : eastNorths) {
116 Way wayToAdd = new Way();
117 for (EastNorth eastNorth : path) {
118 Node nodeToAdd = new Node(Main.getProjection().eastNorth2latlon(eastNorth));
119 // check if new node is not already created by another new path
120 Node nearestNewNode = checkNearestNode(nodeToAdd, svgDataSet.getNodes());
121 if (nearestNewNode == nodeToAdd)
122 svgDataSet.addPrimitive(nearestNewNode);
123 wayToAdd.addNode(nearestNewNode); // either a new node or an existing one
124 }
125 wayToAdd.addNode(wayToAdd.getNode(0)); // close the way
126 svgDataSet.addPrimitive(wayToAdd);
127 }
128
129 // TODO remove small boxes (4 nodes with less than 1 meter distance)
130 /*
131 for (Way w : svgDataSet.ways)
132 if (w.nodes.size() == 5)
133 for (int i = 0; i < w.nodes.size()-2; i++) {
134 if (w.nodes.get(i).eastNorth.distance(w.nodes.get(i+1).eastNorth))
135 }*/
136
137 // simplify ways and check if we can reuse existing OSM nodes
138// for (Way wayToAdd : svgDataSet.getWays())
139// new SimplifyWay().simplifyWay(wayToAdd, svgDataSet, 0.5);
140 // check if the new way or its nodes is already in OSM layer
141 for (Node n : svgDataSet.getNodes()) {
142 Node nearestNewNode = checkNearestNode(n, Main.main.getCurrentDataSet().getNodes());
143 if (nearestNewNode != n) {
144 // replace the SVG node by the OSM node
145 for (Way w : svgDataSet.getWays()) {
146 int replaced = 0;
147 for (Node node : w.getNodes())
148 if (node == n) {
149 node = nearestNewNode;
150 replaced++;
151 }
152 if (w.getNodesCount() == replaced)
153 w.setDeleted(true);
154 }
155 n.setDeleted(true);
156 }
157
158 }
159
160 Collection<Command> cmds = new LinkedList<>();
161 for (Node node : svgDataSet.getNodes())
162 if (!node.isDeleted())
163 cmds.add(new AddCommand(node));
164 for (Way way : svgDataSet.getWays())
165 if (!way.isDeleted())
166 cmds.add(new AddCommand(way));
167 Main.main.undoRedo.add(new SequenceCommand(tr("Create buildings"), cmds));
168 Main.map.repaint();
169 }
170
171 private void createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
172 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
173 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
174 double dx = Double.parseDouble(coor[1]);
175 double dy = Double.parseDouble(coor[2]);
176 for (int i=3; i<coor.length; i+=2){
177 if (coor[i].equals("")) {
178 eastNorth.clear(); // some paths are just artifacts
179 return;
180 }
181 double east = dx+=Double.parseDouble(coor[i]);
182 double north = dy+=Double.parseDouble(coor[i+1]);
183 eastNorth.add(new EastNorth(east,north));
184 }
185 // flip the image (svg using a reversed Y coordinate system)
186 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
187 for (int i = 0; i < eastNorth.size(); i++) {
188 EastNorth en = eastNorth.get(i);
189 eastNorth.set(i, new EastNorth(en.east(), 2 * pivot - en.north()));
190 }
191 return;
192 }
193
194 /**
195 * Check if node can be reused.
196 * @param nodeToAdd the candidate as new node
197 * @return the already existing node (if any), otherwise the new node candidate.
198 */
199 private Node checkNearestNode(Node nodeToAdd, Collection<Node> nodes) {
200 double epsilon = 0.05; // smallest distance considering duplicate node
201 for (Node n : nodes) {
202 if (!n.isDeleted() && !n.isIncomplete()) {
203 double dist = n.getEastNorth().distance(nodeToAdd.getEastNorth());
204 if (dist < epsilon) {
205 return n;
206 }
207 }
208 }
209 return nodeToAdd;
210 }
211
212 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
213 try {
214 URL url = null;
215 url = getURLsvg(bbox);
216 return grabSVG(url);
217 } catch (MalformedURLException e) {
218 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
219 }
220 }
221
222 private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
223 String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
224 str += "&layers=";
225 str += "CDIF:LS2";
226 str += "&format=image/svg";
227 str += "&bbox="+bbox.min.east()+",";
228 str += bbox.min.north() + ",";
229 str += bbox.max.east() + ",";
230 str += bbox.max.north();
231 str += "&width="+CadastrePlugin.imageWidth+"&height="+CadastrePlugin.imageHeight;
232 str += "&exception=application/vnd.ogc.se_inimage";
233 str += "&styles=";
234 str += "LS2_90";
235 Main.info("URL="+str);
236 return new URL(str.replace(" ", "%20"));
237 }
238
239 private String grabSVG(URL url) throws IOException, OsmTransferException {
240 wmsInterface.urlConn = (HttpURLConnection)url.openConnection();
241 wmsInterface.urlConn.setRequestProperty("Connection", "close");
242 wmsInterface.urlConn.setRequestMethod("GET");
243 wmsInterface.setCookie();
244 File file = new File(CadastrePlugin.cacheDir + "building.svg");
245 String svg = new String();
246 try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
247 if (file.exists())
248 file.delete();
249 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
250 InputStreamReader isr = new InputStreamReader(is);
251 BufferedReader br = new BufferedReader(isr)) {
252 String line="";
253 while ( null!=(line=br.readLine())){
254 line += "\n";
255 bos.write(line.getBytes());
256 svg += line;
257 }
258 }
259 } catch (IOException e) {
260 Main.error(e);
261 }
262 return svg;
263 }
264
265 public static void download(WMSLayer wmsLayer) {
266 MapView mv = Main.map.mapView;
267 currentView = new EastNorthBound(mv.getEastNorth(0, mv.getHeight()),
268 mv.getEastNorth(mv.getWidth(), 0));
269 if ((currentView.max.east() - currentView.min.east()) > 1000 ||
270 (currentView.max.north() - currentView.min.north() > 1000)) {
271 JOptionPane.showMessageDialog(Main.parent,
272 tr("To avoid cadastre WMS overload,\nbuilding import size is limited to 1 km2 max."));
273 return;
274 }
275 if (CadastrePlugin.autoSourcing == false) {
276 JOptionPane.showMessageDialog(Main.parent,
277 tr("Please, enable auto-sourcing and check cadastre millesime."));
278 return;
279 }
280 Main.worker.execute(new DownloadSVGBuilding(wmsLayer));
281 if (errorMessage != null)
282 JOptionPane.showMessageDialog(Main.parent, errorMessage);
283 }
284
285}
Note: See TracBrowser for help on using the repository browser.