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

Last change on this file since 29784 was 28961, checked in by pieren, 12 years ago

#8175 change http connection property as closable to avoid connections handup with cadastre server.

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