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

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

checkstyle

File size: 11.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
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 }
155 if (w.getNodesCount() == replaced)
156 w.setDeleted(true);
157 }
158 n.setDeleted(true);
159 }
160
161 }
162
163 Collection<Command> cmds = new LinkedList<>();
164 for (Node node : svgDataSet.getNodes()) {
165 if (!node.isDeleted())
166 cmds.add(new AddCommand(node));
167 }
168 for (Way way : svgDataSet.getWays()) {
169 if (!way.isDeleted())
170 cmds.add(new AddCommand(way));
171 }
172 Main.main.undoRedo.add(new SequenceCommand(tr("Create buildings"), cmds));
173 Main.map.repaint();
174 }
175
176 private void createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
177 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
178 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
179 double dx = Double.parseDouble(coor[1]);
180 double dy = Double.parseDouble(coor[2]);
181 for (int i = 3; i < coor.length; i += 2) {
182 if (coor[i].isEmpty()) {
183 eastNorth.clear(); // some paths are just artifacts
184 return;
185 }
186 double east = dx += Double.parseDouble(coor[i]);
187 double north = dy += Double.parseDouble(coor[i+1]);
188 eastNorth.add(new EastNorth(east, north));
189 }
190 // flip the image (svg using a reversed Y coordinate system)
191 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
192 for (int i = 0; i < eastNorth.size(); i++) {
193 EastNorth en = eastNorth.get(i);
194 eastNorth.set(i, new EastNorth(en.east(), 2 * pivot - en.north()));
195 }
196 return;
197 }
198
199 /**
200 * Check if node can be reused.
201 * @param nodeToAdd the candidate as new node
202 * @return the already existing node (if any), otherwise the new node candidate.
203 */
204 private static Node checkNearestNode(Node nodeToAdd, Collection<Node> nodes) {
205 double epsilon = 0.05; // smallest distance considering duplicate node
206 for (Node n : nodes) {
207 if (!n.isDeleted() && !n.isIncomplete()) {
208 double dist = n.getEastNorth().distance(nodeToAdd.getEastNorth());
209 if (dist < epsilon) {
210 return n;
211 }
212 }
213 }
214 return nodeToAdd;
215 }
216
217 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
218 try {
219 URL url = null;
220 url = getURLsvg(bbox);
221 return grabSVG(url);
222 } catch (MalformedURLException e) {
223 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
224 }
225 }
226
227 private static URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
228 String str = CadastreInterface.BASE_URL+"/scpc/wms?version=1.1&request=GetMap";
229 str += "&layers=";
230 str += "CDIF:LS2";
231 str += "&format=image/svg";
232 str += "&bbox="+bbox.min.east()+",";
233 str += bbox.min.north() + ",";
234 str += bbox.max.east() + ",";
235 str += bbox.max.north();
236 str += "&width="+CadastrePlugin.imageWidth+"&height="+CadastrePlugin.imageHeight;
237 str += "&exception=application/vnd.ogc.se_inimage";
238 str += "&styles=";
239 str += "LS2_90";
240 Main.info("URL="+str);
241 return new URL(str.replace(" ", "%20"));
242 }
243
244 private String grabSVG(URL url) throws IOException, OsmTransferException {
245 wmsInterface.urlConn = (HttpURLConnection) url.openConnection();
246 wmsInterface.urlConn.setRequestProperty("Connection", "close");
247 wmsInterface.urlConn.setRequestMethod("GET");
248 wmsInterface.setCookie();
249 File file = new File(CadastrePlugin.cacheDir + "building.svg");
250 String svg = "";
251 try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
252 if (file.exists())
253 file.delete();
254 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
255 InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
256 BufferedReader br = new BufferedReader(isr)) {
257 String line;
258 while (null != (line = br.readLine())) {
259 line += "\n";
260 bos.write(line.getBytes(StandardCharsets.UTF_8));
261 svg += line;
262 }
263 }
264 } catch (IOException e) {
265 Main.error(e);
266 }
267 return svg;
268 }
269
270 public static void download(WMSLayer wmsLayer) {
271 MapView mv = Main.map.mapView;
272 currentView = new EastNorthBound(mv.getEastNorth(0, mv.getHeight()),
273 mv.getEastNorth(mv.getWidth(), 0));
274 if ((currentView.max.east() - currentView.min.east()) > 1000 ||
275 (currentView.max.north() - currentView.min.north() > 1000)) {
276 JOptionPane.showMessageDialog(Main.parent,
277 tr("To avoid cadastre WMS overload,\nbuilding import size is limited to 1 km2 max."));
278 return;
279 }
280 if (CadastrePlugin.autoSourcing == false) {
281 JOptionPane.showMessageDialog(Main.parent,
282 tr("Please, enable auto-sourcing and check cadastre millesime."));
283 return;
284 }
285 Main.worker.execute(new DownloadSVGBuilding(wmsLayer));
286 if (errorMessage != null)
287 JOptionPane.showMessageDialog(Main.parent, errorMessage);
288 }
289
290}
Note: See TracBrowser for help on using the repository browser.