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

Last change on this file since 32425 was 32425, checked in by donvip, 8 years ago

remove calls to deprecated methods

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