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
RevLine 
[32556]1// License: GPL. For details, see LICENSE file.
[13545]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;
[32211]16import java.nio.charset.StandardCharsets;
[13545]17import java.util.ArrayList;
18import java.util.Collection;
19import java.util.Collections;
20import java.util.LinkedList;
21import java.util.List;
22
[13784]23import javax.swing.JOptionPane;
24
[13545]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;
[16581]33import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
[15961]34import org.openstreetmap.josm.io.OsmTransferException;
[13545]35import org.openstreetmap.josm.io.ProgressInputStream;
36/**
[15961]37 * Grab the SVG administrative boundaries of the active commune layer (cadastre),
[13545]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;
[32211]46 private String svg;
47 private EastNorthBound viewBox;
[20412]48 private static String errorMessage;
[15961]49
[30738]50 /**
51 * Constructs a new {@code DownloadSVGTask}.
52 */
[13545]53 public DownloadSVGTask(WMSLayer wmsLayer) {
[17089]54 super(tr("Downloading {0}", wmsLayer.getName()));
[13545]55
56 this.wmsLayer = wmsLayer;
[25045]57 this.wmsInterface = wmsLayer.grabber.getWmsInterface();
[13545]58 }
59
60 @Override
[15961]61 public void realRun() throws IOException, OsmTransferException {
[23190]62 progressMonitor.indeterminateSubTask(tr("Contacting WMS Server..."));
[20412]63 errorMessage = null;
[13545]64 try {
65 if (wmsInterface.retrieveInterface(wmsLayer)) {
66 svg = grabBoundary(wmsLayer.getCommuneBBox());
67 if (svg == null)
68 return;
[16581]69 progressMonitor.indeterminateSubTask(tr("Extract SVG ViewBox..."));
[13545]70 getViewBox(svg);
71 if (viewBox == null)
72 return;
[16581]73 progressMonitor.indeterminateSubTask(tr("Extract best fitting boundary..."));
[13545]74 createWay(svg);
75 }
76 } catch (DuplicateLayerException e) {
[32060]77 Main.warn("removed a duplicated layer");
[20412]78 } catch (WMSException e) {
79 errorMessage = e.getMessage();
[25045]80 wmsLayer.grabber.getWmsInterface().resetCookie();
[13545]81 }
82 }
83
84 @Override
85 protected void cancel() {
[25045]86 wmsLayer.grabber.getWmsInterface().cancel();
[13545]87 }
88
89 @Override
90 protected void finish() {
[32211]91 // Do nothing
[13545]92 }
93
94 private boolean getViewBox(String svg) {
95 double[] box = new SVGParser().getViewBox(svg);
96 if (box != null) {
[15961]97 viewBox = new EastNorthBound(new EastNorth(box[0], box[1]),
[13545]98 new EastNorth(box[0]+box[2], box[1]+box[3]));
99 return true;
100 }
[30859]101 Main.warn("Unable to parse SVG data (viewBox)");
[13545]102 return false;
103 }
[15961]104
[13545]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) {
[13784]110 String[] SVGpaths = new SVGParser().getClosedPaths(svg);
[30737]111 ArrayList<Double> fitViewBox = new ArrayList<>();
112 ArrayList<ArrayList<EastNorth>> eastNorths = new ArrayList<>();
[32556]113 for (int i = 0; i < SVGpaths.length; i++) {
[30737]114 ArrayList<EastNorth> eastNorth = new ArrayList<>();
[32556]115 fitViewBox.add(createNodes(SVGpaths[i], eastNorth));
[13545]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);
[30737]121 List<Node> nodeList = new ArrayList<>();
[13545]122 for (EastNorth eastNorth : eastNorths.get(bestPath)) {
[26228]123 nodeList.add(new Node(Main.getProjection().eastNorth2latlon(eastNorth)));
[13545]124 }
125 Way wayToAdd = new Way();
[30737]126 Collection<Command> cmds = new LinkedList<>();
[13545]127 for (Node node : nodeList) {
128 cmds.add(new AddCommand(node));
[17365]129 wayToAdd.addNode(node);
[13545]130 }
[17365]131 wayToAdd.addNode(wayToAdd.getNode(0)); // close the circle
[15961]132
[13784]133 // simplify the way
[20390]134// double threshold = Double.parseDouble(Main.pref.get("cadastrewms.simplify-way-boundary", "1.0"));
135// new SimplifyWay().simplifyWay(wayToAdd, Main.main.getCurrentDataSet(), threshold);
[15961]136
[13545]137 cmds.add(new AddCommand(wayToAdd));
138 Main.main.undoRedo.add(new SequenceCommand(tr("Create boundary"), cmds));
139 Main.map.repaint();
140 }
[15961]141
[13545]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;
[32556]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));
[15961]155 minX = minX > east ? east : minX;
156 minY = minY > north ? north : minY;
157 maxX = maxX < east ? east : maxX;
158 maxY = maxY < north ? north : maxY;
[13545]159 }
[15961]160 // flip the image (svg using a reversed Y coordinate system)
[13545]161 double pivot = viewBox.min.getY() + (viewBox.max.getY() - viewBox.min.getY()) / 2;
[29854]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()));
[13545]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
[15961]170 private String grabBoundary(EastNorthBound bbox) throws IOException, OsmTransferException {
[13545]171 try {
[32211]172 return grabSVG(getURLsvg(bbox));
[13545]173 } catch (MalformedURLException e) {
174 throw (IOException) new IOException(tr("CadastreGrabber: Illegal url.")).initCause(e);
175 }
176 }
[15961]177
[32211]178 private static URL getURLsvg(EastNorthBound bbox) throws MalformedURLException {
179 String str = CadastreInterface.BASE_URL+"/scpc/wms?version=1.1&request=GetMap";
[13545]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();
[20240]187 str += "&width="+CadastrePlugin.imageWidth+"&height="+CadastrePlugin.imageHeight;
[13545]188 str += "&styles=";
189 str += "COMMUNE_90";
[30859]190 Main.info("URL="+str);
[13545]191 return new URL(str.replace(" ", "%20"));
192 }
193
[15961]194 private String grabSVG(URL url) throws IOException, OsmTransferException {
[32556]195 wmsInterface.urlConn = (HttpURLConnection) url.openConnection();
[28961]196 wmsInterface.urlConn.setRequestProperty("Connection", "close");
[13545]197 wmsInterface.urlConn.setRequestMethod("GET");
198 wmsInterface.setCookie();
199 File file = new File(CadastrePlugin.cacheDir + "boundary.svg");
[32211]200 String svg = "";
[30738]201 try (InputStream is = new ProgressInputStream(wmsInterface.urlConn, NullProgressMonitor.INSTANCE)) {
[13545]202 if (file.exists())
203 file.delete();
[30738]204 try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, true));
[32556]205 InputStreamReader isr = new InputStreamReader(is);
[30738]206 BufferedReader br = new BufferedReader(isr)) {
[32211]207 String line;
[32556]208 while (null != (line = br.readLine())) {
[30738]209 line += "\n";
[32211]210 bos.write(line.getBytes(StandardCharsets.UTF_8));
[30738]211 svg += line;
212 }
[13545]213 }
214 } catch (IOException e) {
[30738]215 Main.error(e);
[13545]216 }
217 return svg;
218 }
219
220 public static void download(WMSLayer wmsLayer) {
[32211]221 if (!CadastrePlugin.autoSourcing) {
[13784]222 JOptionPane.showMessageDialog(Main.parent,
223 tr("Please, enable auto-sourcing and check cadastre millesime."));
224 return;
225 }
[13545]226 Main.worker.execute(new DownloadSVGTask(wmsLayer));
[20412]227 if (errorMessage != null)
228 JOptionPane.showMessageDialog(Main.parent, errorMessage);
[13545]229 }
230}
Note: See TracBrowser for help on using the repository browser.