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

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

remove tabs

File size: 9.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.Collections;
19import java.util.LinkedList;
20import java.util.List;
21
22import javax.swing.JOptionPane;
23
24import org.openstreetmap.josm.Main;
25import org.openstreetmap.josm.command.AddCommand;
26import org.openstreetmap.josm.command.Command;
27import org.openstreetmap.josm.command.SequenceCommand;
28import org.openstreetmap.josm.data.coor.EastNorth;
29import org.openstreetmap.josm.data.osm.Node;
30import org.openstreetmap.josm.data.osm.Way;
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/**
36 * Grab the SVG administrative boundaries of the active commune layer (cadastre),
37 * isolate the SVG path of the concerned commune (other municipalities are also
38 * downloaded in the SVG data), convert to OSM nodes and way plus simplify.
39 * Thanks to Frederic Rodrigo for his help.
40 */
41public class DownloadSVGTask extends PleaseWaitRunnable {
42
43 private WMSLayer wmsLayer;
44 private CadastreInterface wmsInterface;
45 private String svg = null;
46 private EastNorthBound viewBox = null;
47 private static String errorMessage;
48
49 /**
50 * Constructs a new {@code DownloadSVGTask}.
51 */
52 public DownloadSVGTask(WMSLayer wmsLayer) {
53 super(tr("Downloading {0}", wmsLayer.getName()));
54
55 this.wmsLayer = wmsLayer;
56 this.wmsInterface = wmsLayer.grabber.getWmsInterface();
57 }
58
59 @Override
60 public void realRun() throws IOException, OsmTransferException {
61 progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
62 errorMessage = null;
63 try {
64 if (wmsInterface.retrieveInterface(wmsLayer)) {
65 svg = grabBoundary(wmsLayer.getCommuneBBox());
66 if (svg == null)
67 return;
68 progressMonitor.indeterminateSubTask(tr("Extract SVG ViewBox..."));
69 getViewBox(svg);
70 if (viewBox == null)
71 return;
72 progressMonitor.indeterminateSubTask(tr("Extract best fitting boundary..."));
73 createWay(svg);
74 }
75 } catch (DuplicateLayerException e) {
76 Main.warn("removed a duplicated layer");
77 } catch (WMSException e) {
78 errorMessage = e.getMessage();
79 wmsLayer.grabber.getWmsInterface().resetCookie();
80 }
81 }
82
83 @Override
84 protected void cancel() {
85 wmsLayer.grabber.getWmsInterface().cancel();
86 }
87
88 @Override
89 protected void finish() {
90 }
91
92 private boolean getViewBox(String svg) {
93 double[] box = new SVGParser().getViewBox(svg);
94 if (box != null) {
95 viewBox = new EastNorthBound(new EastNorth(box[0], box[1]),
96 new EastNorth(box[0]+box[2], box[1]+box[3]));
97 return true;
98 }
99 Main.warn("Unable to parse SVG data (viewBox)");
100 return false;
101 }
102
103 /**
104 * The svg contains more than one commune boundary defined by path elements. So detect
105 * which path element is the best fitting to the viewBox and convert it to OSM objects
106 */
107 private void createWay(String svg) {
108 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
109 ArrayList<Double> fitViewBox = new ArrayList<>();
110 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<>();
111 for (int i=0; i< SVGpaths.length; i++) {
112 ArrayList<EastNorth> eastNorth = new ArrayList<>();
113 fitViewBox.add( createNodes(SVGpaths[i], eastNorth) );
114 eastNorths.add(eastNorth);
115 }
116 // the smallest fitViewBox indicates the best fitting path in viewBox
117 Double min = Collections.min(fitViewBox);
118 int bestPath = fitViewBox.indexOf(min);
119 List<Node> nodeList = new ArrayList<>();
120 for (EastNorth eastNorth : eastNorths.get(bestPath)) {
121 nodeList.add(new Node(Main.getProjection().eastNorth2latlon(eastNorth)));
122 }
123 Way wayToAdd = new Way();
124 Collection<Command> cmds = new LinkedList<>();
125 for (Node node : nodeList) {
126 cmds.add(new AddCommand(node));
127 wayToAdd.addNode(node);
128 }
129 wayToAdd.addNode(wayToAdd.getNode(0)); // close the circle
130
131 // simplify the way
132// double threshold = Double.parseDouble(Main.pref.get("cadastrewms.simplify-way-boundary", "1.0"));
133// new SimplifyWay().simplifyWay(wayToAdd, Main.main.getCurrentDataSet(), threshold);
134
135 cmds.add(new AddCommand(wayToAdd));
136 Main.main.undoRedo.add(new SequenceCommand(tr("Create boundary"), cmds));
137 Main.map.repaint();
138 }
139
140 private double createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
141 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
142 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
143 double dx = Double.parseDouble(coor[1]);
144 double dy = Double.parseDouble(coor[2]);
145 double minY = Double.MAX_VALUE;
146 double minX = Double.MAX_VALUE;
147 double maxY = Double.MIN_VALUE;
148 double maxX = Double.MIN_VALUE;
149 for (int i=3; i<coor.length; i+=2){
150 double east = dx+=Double.parseDouble(coor[i]);
151 double north = dy+=Double.parseDouble(coor[i+1]);
152 eastNorth.add(new EastNorth(east,north));
153 minX = minX > east ? east : minX;
154 minY = minY > north ? north : minY;
155 maxX = maxX < east ? east : maxX;
156 maxY = maxY < north ? north : maxY;
157 }
158 // flip the image (svg using a reversed Y coordinate system)
159 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
160 for (int i = 0; i < eastNorth.size(); i++) {
161 EastNorth en = eastNorth.get(i);
162 eastNorth.set(i, new EastNorth(en.east(), 2 * pivot - en.north()));
163 }
164 return Math.abs(minX - viewBox.min.getX())+Math.abs(maxX - viewBox.max.getX())
165 +Math.abs(minY - viewBox.min.getY())+Math.abs(maxY - viewBox.max.getY());
166 }
167
168 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
169 try {
170 URL url = null;
171 url = getURLsvg(bbox);
172 return grabSVG(url);
173 } catch (MalformedURLException e) {
174 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
175 }
176 }
177
178 private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
179 String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
180 str += "&layers=";
181 str += "CDIF:COMMUNE";
182 str += "&format=image/svg";
183 str += "&bbox="+bbox.min.east()+",";
184 str += bbox.min.north() + ",";
185 str += bbox.max.east() + ",";
186 str += bbox.max.north();
187 str += "&width="+CadastrePlugin.imageWidth+"&height="+CadastrePlugin.imageHeight;
188 str += "&styles=";
189 str += "COMMUNE_90";
190 Main.info("URL="+str);
191 return new URL(str.replace(" ", "%20"));
192 }
193
194 private String grabSVG(URL url) throws IOException, OsmTransferException {
195 wmsInterface.urlConn = (HttpURLConnection)url.openConnection();
196 wmsInterface.urlConn.setRequestProperty("Connection", "close");
197 wmsInterface.urlConn.setRequestMethod("GET");
198 wmsInterface.setCookie();
199 File file = new File(CadastrePlugin.cacheDir + "boundary.svg");
200 String svg = new String();
201 try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
202 if (file.exists())
203 file.delete();
204 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
205 InputStreamReader isr =new InputStreamReader(is);
206 BufferedReader br = new BufferedReader(isr)) {
207 String line="";
208 while ( null!=(line=br.readLine())){
209 line += "\n";
210 bos.write(line.getBytes());
211 svg += line;
212 }
213 }
214 } catch (IOException e) {
215 Main.error(e);
216 }
217 return svg;
218 }
219
220 public static void download(WMSLayer wmsLayer) {
221 if (CadastrePlugin.autoSourcing == false) {
222 JOptionPane.showMessageDialog(Main.parent,
223 tr("Please, enable auto-sourcing and check cadastre millesime."));
224 return;
225 }
226 Main.worker.execute(new DownloadSVGTask(wmsLayer));
227 if (errorMessage != null)
228 JOptionPane.showMessageDialog(Main.parent, errorMessage);
229 }
230
231}
Note: See TracBrowser for help on using the repository browser.