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

Last change on this file since 21777 was 20412, checked in by pieren, 15 years ago

improve download cancellation

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