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

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

checkstyle

File size: 9.3 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.Collections;
20import java.util.LinkedList;
21import java.util.List;
22
23import javax.swing.JOptionPane;
24
25import org.openstreetmap.josm.Main;
26import org.openstreetmap.josm.command.AddCommand;
27import org.openstreetmap.josm.command.Command;
28import org.openstreetmap.josm.command.SequenceCommand;
29import org.openstreetmap.josm.data.coor.EastNorth;
30import org.openstreetmap.josm.data.osm.Node;
31import org.openstreetmap.josm.data.osm.Way;
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/**
37 * Grab the SVG administrative boundaries of the active commune layer (cadastre),
38 * isolate the SVG path of the concerned commune (other municipalities are also
39 * downloaded in the SVG data), convert to OSM nodes and way plus simplify.
40 * Thanks to Frederic Rodrigo for his help.
41 */
42public class DownloadSVGTask extends PleaseWaitRunnable {
43
44 private WMSLayer wmsLayer;
45 private CadastreInterface wmsInterface;
46 private String svg;
47 private EastNorthBound viewBox;
48 private static String errorMessage;
49
50 /**
51 * Constructs a new {@code DownloadSVGTask}.
52 */
53 public DownloadSVGTask(WMSLayer wmsLayer) {
54 super(tr("Downloading {0}", wmsLayer.getName()));
55
56 this.wmsLayer = wmsLayer;
57 this.wmsInterface = wmsLayer.grabber.getWmsInterface();
58 }
59
60 @Override
61 public void realRun() throws IOException, OsmTransferException {
62 progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
63 errorMessage = null;
64 try {
65 if (wmsInterface.retrieveInterface(wmsLayer)) {
66 svg = grabBoundary(wmsLayer.getCommuneBBox());
67 if (svg == null)
68 return;
69 progressMonitor.indeterminateSubTask(tr("Extract SVG ViewBox..."));
70 getViewBox(svg);
71 if (viewBox == null)
72 return;
73 progressMonitor.indeterminateSubTask(tr("Extract best fitting boundary..."));
74 createWay(svg);
75 }
76 } catch (DuplicateLayerException e) {
77 Main.warn("removed a duplicated layer");
78 } catch (WMSException e) {
79 errorMessage = e.getMessage();
80 wmsLayer.grabber.getWmsInterface().resetCookie();
81 }
82 }
83
84 @Override
85 protected void cancel() {
86 wmsLayer.grabber.getWmsInterface().cancel();
87 }
88
89 @Override
90 protected void finish() {
91 // Do nothing
92 }
93
94 private boolean getViewBox(String svg) {
95 double[] box = new SVGParser().getViewBox(svg);
96 if (box != null) {
97 viewBox = new EastNorthBound(new EastNorth(box[0], box[1]),
98 new EastNorth(box[0]+box[2], box[1]+box[3]));
99 return true;
100 }
101 Main.warn("Unable to parse SVG data (viewBox)");
102 return false;
103 }
104
105 /**
106 * The svg contains more than one commune boundary defined by path elements. So detect
107 * which path element is the best fitting to the viewBox and convert it to OSM objects
108 */
109 private void createWay(String svg) {
110 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
111 ArrayList<Double> fitViewBox = new ArrayList<>();
112 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<>();
113 for (int i = 0; i < SVGpaths.length; i++) {
114 ArrayList<EastNorth> eastNorth = new ArrayList<>();
115 fitViewBox.add(createNodes(SVGpaths[i], eastNorth));
116 eastNorths.add(eastNorth);
117 }
118 // the smallest fitViewBox indicates the best fitting path in viewBox
119 Double min = Collections.min(fitViewBox);
120 int bestPath = fitViewBox.indexOf(min);
121 List<Node> nodeList = new ArrayList<>();
122 for (EastNorth eastNorth : eastNorths.get(bestPath)) {
123 nodeList.add(new Node(Main.getProjection().eastNorth2latlon(eastNorth)));
124 }
125 Way wayToAdd = new Way();
126 Collection<Command> cmds = new LinkedList<>();
127 for (Node node : nodeList) {
128 cmds.add(new AddCommand(node));
129 wayToAdd.addNode(node);
130 }
131 wayToAdd.addNode(wayToAdd.getNode(0)); // close the circle
132
133 // simplify the way
134// double threshold = Double.parseDouble(Main.pref.get("cadastrewms.simplify-way-boundary", "1.0"));
135// new SimplifyWay().simplifyWay(wayToAdd, Main.main.getCurrentDataSet(), threshold);
136
137 cmds.add(new AddCommand(wayToAdd));
138 Main.main.undoRedo.add(new SequenceCommand(tr("Create boundary"), cmds));
139 Main.map.repaint();
140 }
141
142 private double createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
143 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
144 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
145 double dx = Double.parseDouble(coor[1]);
146 double dy = Double.parseDouble(coor[2]);
147 double minY = Double.MAX_VALUE;
148 double minX = Double.MAX_VALUE;
149 double maxY = Double.MIN_VALUE;
150 double maxX = Double.MIN_VALUE;
151 for (int i = 3; i < coor.length; i += 2) {
152 double east = dx += Double.parseDouble(coor[i]);
153 double north = dy += Double.parseDouble(coor[i+1]);
154 eastNorth.add(new EastNorth(east, north));
155 minX = minX > east ? east : minX;
156 minY = minY > north ? north : minY;
157 maxX = maxX < east ? east : maxX;
158 maxY = maxY < north ? north : maxY;
159 }
160 // flip the image (svg using a reversed Y coordinate system)
161 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
162 for (int i = 0; i < eastNorth.size(); i++) {
163 EastNorth en = eastNorth.get(i);
164 eastNorth.set(i, new EastNorth(en.east(), 2 * pivot - en.north()));
165 }
166 return Math.abs(minX - viewBox.min.getX())+Math.abs(maxX - viewBox.max.getX())
167 +Math.abs(minY - viewBox.min.getY())+Math.abs(maxY - viewBox.max.getY());
168 }
169
170 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
171 try {
172 return grabSVG(getURLsvg(bbox));
173 } catch (MalformedURLException e) {
174 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
175 }
176 }
177
178 private static URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
179 String str = CadastreInterface.BASE_URL+"/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 = "";
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(StandardCharsets.UTF_8));
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) {
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}
Note: See TracBrowser for help on using the repository browser.