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

Last change on this file since 16581 was 16581, checked in by jttt, 15 years ago

Made work with JOSM new ProgressMonitor

File size: 8.8 KB
Line 
1package cadastre_fr;
2
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.io.BufferedOutputStream;
6import java.io.BufferedReader;
7import java.io.File;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.net.HttpURLConnection;
13import java.net.MalformedURLException;
14import java.net.URL;
15import java.util.ArrayList;
16import java.util.Collection;
17import java.util.Collections;
18import java.util.LinkedList;
19import java.util.List;
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.Node;
29import org.openstreetmap.josm.data.osm.Way;
30import org.openstreetmap.josm.gui.PleaseWaitRunnable;
31import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
32import org.openstreetmap.josm.io.OsmTransferException;
33import org.openstreetmap.josm.io.ProgressInputStream;
34/**
35 * Grab the SVG administrative boundaries of the active commune layer (cadastre),
36 * isolate the SVG path of the concerned commune (other municipalities are also
37 * downloaded in the SVG data), convert to OSM nodes and way plus simplify.
38 * Thanks to Frederic Rodrigo for his help.
39 */
40public class DownloadSVGTask extends PleaseWaitRunnable {
41
42 private WMSLayer wmsLayer;
43 private CadastreGrabber grabber = CadastrePlugin.cadastreGrabber;
44 private CadastreInterface wmsInterface;
45 private String svg = null;
46 private EastNorthBound viewBox = null;
47
48 public DownloadSVGTask(WMSLayer wmsLayer) {
49 super(tr("Downloading {0}", wmsLayer.name));
50
51 this.wmsLayer = wmsLayer;
52 this.wmsInterface = grabber.getWmsInterface();
53 }
54
55 @Override
56 public void realRun() throws IOException, OsmTransferException {
57 progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
58 try {
59 if (wmsInterface.retrieveInterface(wmsLayer)) {
60 svg = grabBoundary(wmsLayer.getCommuneBBox());
61 if (svg == null)
62 return;
63 progressMonitor.indeterminateSubTask(tr("Extract SVG ViewBox..."));
64 getViewBox(svg);
65 if (viewBox == null)
66 return;
67 progressMonitor.indeterminateSubTask(tr("Extract best fitting boundary..."));
68 createWay(svg);
69 }
70 } catch (DuplicateLayerException e) {
71 System.err.println("removed a duplicated layer");
72 }
73 }
74
75 @Override
76 protected void cancel() {
77 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 createWay(String svg) {
100 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
101 ArrayList<Double> fitViewBox = new ArrayList<Double>();
102 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<ArrayList<EastNorth>>();
103 for (int i=0; i< SVGpaths.length; i++) {
104 ArrayList<EastNorth> eastNorth = new ArrayList<EastNorth>();
105 fitViewBox.add( createNodes(SVGpaths[i], eastNorth) );
106 eastNorths.add(eastNorth);
107 }
108 // the smallest fitViewBox indicates the best fitting path in viewBox
109 Double min = Collections.min(fitViewBox);
110 int bestPath = fitViewBox.indexOf(min);
111 List<Node> nodeList = new ArrayList<Node>();
112 for (EastNorth eastNorth : eastNorths.get(bestPath)) {
113 nodeList.add(new Node(Main.proj.eastNorth2latlon(eastNorth)));
114 }
115 Way wayToAdd = new Way();
116 Collection<Command> cmds = new LinkedList<Command>();
117 for (Node node : nodeList) {
118 cmds.add(new AddCommand(node));
119 wayToAdd.nodes.add(node);
120 }
121 wayToAdd.nodes.add(wayToAdd.nodes.get(0)); // close the circle
122
123 // simplify the way
124 double threshold = Double.parseDouble(Main.pref.get("cadastrewms.simplify-way-boundary", "1.0"));
125 new SimplifyWay().simplifyWay(wayToAdd, Main.ds, threshold);
126
127 cmds.add(new AddCommand(wayToAdd));
128 Main.main.undoRedo.add(new SequenceCommand(tr("Create boundary"), cmds));
129 Main.map.repaint();
130 }
131
132 private double createNodes(String SVGpath, ArrayList<EastNorth> eastNorth) {
133 // looks like "M981283.38 368690.15l143.81 72.46 155.86 ..."
134 String[] coor = SVGpath.split("[MlZ ]"); //coor[1] is x, coor[2] is y
135 double dx = Double.parseDouble(coor[1]);
136 double dy = Double.parseDouble(coor[2]);
137 double minY = Double.MAX_VALUE;
138 double minX = Double.MAX_VALUE;
139 double maxY = Double.MIN_VALUE;
140 double maxX = Double.MIN_VALUE;
141 for (int i=3; i<coor.length; i+=2){
142 double east = dx+=Double.parseDouble(coor[i]);
143 double north = dy+=Double.parseDouble(coor[i+1]);
144 eastNorth.add(new EastNorth(east,north));
145 minX = minX > east ? east : minX;
146 minY = minY > north ? north : minY;
147 maxX = maxX < east ? east : maxX;
148 maxY = maxY < north ? north : maxY;
149 }
150 // flip the image (svg using a reversed Y coordinate system)
151 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
152 for (EastNorth en : eastNorth) {
153 en.setLocation(en.east(), 2 * pivot - en.north());
154 }
155 return Math.abs(minX - viewBox.min.getX())+Math.abs(maxX - viewBox.max.getX())
156 +Math.abs(minY - viewBox.min.getY())+Math.abs(maxY - viewBox.max.getY());
157 }
158
159 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
160 try {
161 URL url = null;
162 url = getURLsvg(bbox);
163 System.out.println("grab:"+url);
164 return grabSVG(url);
165 } catch (MalformedURLException e) {
166 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
167 }
168 }
169
170 private URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
171 String str = new String(wmsInterface.baseURL+"/scpc/wms?version=1.1&request=GetMap");
172 str += "&layers=";
173 str += "CDIF:COMMUNE";
174 str += "&format=image/svg";
175 str += "&bbox="+bbox.min.east()+",";
176 str += bbox.min.north() + ",";
177 str += bbox.max.east() + ",";
178 str += bbox.max.north();
179 str += "&width=800&height=600"; // maximum allowed by wms server
180 str += "&styles=";
181 str += "COMMUNE_90";
182 System.out.println("URL="+str);
183 return new URL(str.replace(" ", "%20"));
184 }
185
186 private String grabSVG(URL url) throws IOException, OsmTransferException {
187 wmsInterface.urlConn = (HttpURLConnection)url.openConnection();
188 wmsInterface.urlConn.setRequestMethod("GET");
189 wmsInterface.setCookie();
190 InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE);
191 File file = new File(CadastrePlugin.cacheDir + "boundary.svg");
192 String svg = new String();
193 try {
194 if (file.exists())
195 file.delete();
196 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
197 InputStreamReader isr =new InputStreamReader(is);
198 BufferedReader br = new BufferedReader(isr);
199 String line="";
200 while ( null!=(line=br.readLine())){
201 line += "\n";
202 bos.write(line.getBytes());
203 svg += line;
204 }
205 bos.close();
206 } catch (IOException e) {
207 e.printStackTrace(System.out);
208 }
209 is.close();
210 return svg;
211 }
212
213 public static void download(WMSLayer wmsLayer) {
214 if (CadastrePlugin.autoSourcing == false) {
215 JOptionPane.showMessageDialog(Main.parent,
216 tr("Please, enable auto-sourcing and check cadastre millesime."));
217 return;
218 }
219 Main.worker.execute(new DownloadSVGTask(wmsLayer));
220 }
221
222}
Note: See TracBrowser for help on using the repository browser.