PageRenderTime 24ms CodeModel.GetById 1ms app.highlight 19ms RepoModel.GetById 1ms app.codeStats 0ms

/webportal/src/main/java/org/ala/spatial/analysis/web/AreaUploadShapefile.java

http://alageospatialportal.googlecode.com/
Java | 364 lines | 284 code | 45 blank | 35 comment | 57 complexity | 599afb2e948f1976ab2f40016e71d571 MD5 | raw file
  1package org.ala.spatial.analysis.web;
  2
  3import au.org.emii.portal.composer.MapComposer;
  4import au.org.emii.portal.menu.MapLayer;
  5import au.org.emii.portal.menu.MapLayerMetadata;
  6import java.io.BufferedReader;
  7import java.io.BufferedWriter;
  8import java.io.File;
  9import java.io.FileWriter;
 10import java.io.InputStream;
 11import java.io.InputStreamReader;
 12import java.io.PrintWriter;
 13import java.io.Reader;
 14import java.io.StringReader;
 15import java.io.StringWriter;
 16import java.io.Writer;
 17import java.util.Map;
 18import org.ala.spatial.util.ShapefileUtils;
 19import org.ala.spatial.util.Zipper;
 20import org.zkoss.util.media.Media;
 21import org.zkoss.zk.ui.event.Event;
 22import org.zkoss.zk.ui.event.EventListener;
 23import org.zkoss.zk.ui.event.ForwardEvent;
 24import org.zkoss.zk.ui.event.UploadEvent;
 25import org.zkoss.zul.Textbox;
 26
 27import com.vividsolutions.jts.geom.Geometry;
 28import com.vividsolutions.jts.io.WKTWriter;
 29import java.util.Collection;
 30import java.util.HashMap;
 31import java.util.zip.ZipEntry;
 32import java.util.zip.ZipInputStream;
 33import org.ala.spatial.util.UserData;
 34import org.apache.commons.httpclient.HttpClient;
 35import org.apache.commons.httpclient.UsernamePasswordCredentials;
 36import org.apache.commons.httpclient.auth.AuthScope;
 37import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
 38import org.apache.commons.httpclient.methods.PutMethod;
 39import org.apache.commons.httpclient.methods.RequestEntity;
 40import org.geotools.kml.KMLConfiguration;
 41import org.geotools.xml.Parser;
 42import org.opengis.feature.simple.SimpleFeature;
 43import org.zkoss.zk.ui.Executions;
 44import org.zkoss.zk.ui.SuspendNotAllowedException;
 45import org.zkoss.zul.Button;
 46import org.zkoss.zul.Window;
 47
 48/**
 49 *
 50 * @author Adam
 51 */
 52public class AreaUploadShapefile extends AreaToolComposer {
 53
 54    //Fileupload fileUpload;
 55    Button fileUpload;
 56    Textbox txtLayerName;
 57
 58    @Override
 59    public void afterCompose() {
 60        super.afterCompose();
 61        txtLayerName.setValue(getMapComposer().getNextAreaLayerName("My Area"));
 62        fileUpload.addEventListener("onUpload", new EventListener() {
 63
 64            public void onEvent(Event event) throws Exception {
 65                onClick$btnOk(event);
 66            }
 67        });
 68    }
 69
 70    public void onClick$btnOk(Event event) {
 71        onUpload$btnFileUpload(event);
 72        this.detach();
 73    }
 74
 75    public void onClick$btnCancel(Event event) {
 76        this.detach();
 77    }
 78
 79    public void onUpload$btnFileUpload(Event event) {
 80        //UploadEvent ue = (UploadEvent) ((ForwardEvent) event).getOrigin();
 81        UploadEvent ue = null;
 82        if (event.getName().equals("onUpload")) {
 83            ue = (UploadEvent) event;
 84        } else if (event.getName().equals("onForward")) {
 85            ue = (UploadEvent) ((ForwardEvent) event).getOrigin();
 86        }
 87        if (ue == null) {
 88            System.out.println("unable to upload file");
 89            return;
 90        } else {
 91            System.out.println("fileUploaded()");
 92        }
 93        try {
 94            Media m = ue.getMedia();
 95
 96            System.out.println("m.getName(): " + m.getName());
 97            System.out.println("getContentType: " + m.getContentType());
 98            System.out.println("getFormat: " + m.getFormat());
 99
100            // check the content-type
101//            if (m.getContentType().equalsIgnoreCase("text/plain") || m.getContentType().equalsIgnoreCase(LayersUtil.LAYER_TYPE_CSV) || m.getContentType().equalsIgnoreCase(LayersUtil.LAYER_TYPE_CSV_EXCEL)) {
102//                loadUserPoints(m.getName(), m.getReaderData());
103//            } else if (m.getContentType().equalsIgnoreCase(LayersUtil.LAYER_TYPE_EXCEL)) {
104//                byte[] csvdata = m.getByteData();
105//                loadUserPoints(m.getName(), new StringReader(new String(csvdata)));
106//            } else
107
108//            if (m.getContentType().equalsIgnoreCase(LayersUtil.LAYER_TYPE_KML)) {
109//                System.out.println("isBin: " + m.isBinary());
110//                System.out.println("inMem: " + m.inMemory());
111//                if (m.inMemory()) {
112//                    loadUserLayerKML(m.getName(), m.getByteData());
113//                } else {
114//                    loadUserLayerKML(m.getName(), m.getStreamData());
115//                }
116//              }
117
118            UserData ud = new UserData(txtLayerName.getValue());
119            ud.setFilename(m.getName());
120
121            byte[] kmldata = getKml(m);
122            if (kmldata != null) {
123                loadUserLayerKML(m.getName(), kmldata, ud);
124            //} else if (m.getName().equalsIgnoreCase("MEOW2.zip") || m.getName().equalsIgnoreCase("singlepolygon.zip")) {
125            } else if (m.getName().toLowerCase().endsWith("zip")) {
126                Map args = new HashMap();
127                args.put("layername", txtLayerName.getValue());
128                args.put("media", m);
129                Window window = (Window) Executions.createComponents("WEB-INF/zul/AreaUploadShapefileWizard.zul", this.getParent(), args);
130                try {
131                    window.doModal();
132                } catch (SuspendNotAllowedException e) {
133                    // we are really closing the window without opening/displaying to the user                
134                }
135            } else if (m.getName().toLowerCase().endsWith("zip_removeme")) { //else if (m.getContentType().equalsIgnoreCase(LayersUtil.LAYER_TYPE_ZIP)) {
136                // "/data/ala/runtime/output/layers/"
137                // "/Users/ajay/projects/tmp/useruploads/"
138                Map input = Zipper.unzipFile(m.getName(), m.getStreamData(), "/data/ala/runtime/output/layers/");
139                String type = "";
140                String file = "";
141                if (input.containsKey("type")) {
142                    type = (String) input.get("type");
143                }
144                if (input.containsKey("file")) {
145                    file = (String) input.get("file");
146                }
147                if (type.equalsIgnoreCase("shp")) {
148                    System.out.println("Uploaded file is a shapefile. Loading...");
149                    Map shape = ShapefileUtils.loadShapefile(new File(file));
150
151                    if (shape == null) {
152                        return;
153                    } else {
154                        String wkt = (String) shape.get("wkt");
155                        //wkt = wkt.replace("MULTIPOLYGON (((", "POLYGON((").replaceAll(", ", ",").replace(")))", "))");
156                        System.out.println("Got shapefile wkt...");
157                        //String layerName = getMapComposer().getNextAreaLayerName(txtLayerName.getValue());
158                        layerName = txtLayerName.getValue();
159                        MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layerName, layerName);
160                        mapLayer.setMapLayerMetadata(new MapLayerMetadata());
161                        //mapLayer.getMapLayerMetadata().setMoreInfo("User uploaded shapefile. \n Used polygon: " + shape.get("id"));
162                        //mapLayer.getMapLayerMetadata().setMoreInfo("User uploaded shapefile.");
163
164                        ud.setUploadedTimeInMs(System.currentTimeMillis());
165                        ud.setType("shapefile");
166
167                        String metadata = "";
168                        metadata += "User uploaded Shapefile \n";
169                        metadata += "Name: " + ud.getName() + " <br />\n";
170                        metadata += "Filename: " + ud.getFilename() + " <br />\n";
171                        metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
172
173                        MapLayerMetadata mlmd = mapLayer.getMapLayerMetadata();
174                        if (mlmd == null) {
175                            mlmd = new MapLayerMetadata();
176                        }
177                        mlmd.setMoreInfo(metadata);
178                        mapLayer.setMapLayerMetadata(mlmd);
179
180                        ok = true;
181                    }
182                } else {
183                    System.out.println("Unknown file type. ");
184                    getMapComposer().showMessage("Unknown file type. Please upload a valid CSV, \nKML or Shapefile. ");
185                }
186            } else {
187                System.out.println("Unknown file type. ");
188                getMapComposer().showMessage("Unknown file type. Please upload a valid CSV, \nKML or Shapefile. ");
189            }
190        } catch (Exception ex) {
191            getMapComposer().showMessage("Unable to load file. Please try again. ");
192            ex.printStackTrace();
193        }
194    }
195
196    private byte[] getKml(Media m) {
197        try {
198            String kmlData = "";
199
200            if (m.inMemory()) {
201                kmlData = new String(m.getByteData());
202            } else if (m.isBinary()) {
203                InputStream data = m.getStreamData();
204                if (data != null) {
205                    Writer writer = new StringWriter();
206
207                    char[] buffer = new char[1024];
208                    try {
209                        Reader reader = new BufferedReader(
210                                new InputStreamReader(data));
211                        int n;
212                        while ((n = reader.read(buffer)) != -1) {
213                            writer.write(buffer, 0, n);
214                        }
215                    } finally {
216                        data.close();
217                    }
218                    kmlData = writer.toString();
219                }
220            } else if ("txt".equals(m.getFormat())) {
221                Writer writer = new StringWriter();
222                char[] buffer = new char[1024];
223                try {
224                    Reader reader = m.getReaderData();
225                    int n;
226                    while ((n = reader.read(buffer)) != -1) {
227                        writer.write(buffer, 0, n);
228                    }
229                } finally {
230                }
231                kmlData = writer.toString();
232            }
233
234            if (kmlData.contains("xml") && kmlData.contains("Document")) { // kmlData.contains("kml") && 
235                return kmlData.getBytes();
236            } else {
237                return null;
238            }
239        } catch (Exception e) {
240            System.out.println("Exception checking if kml file");
241            e.printStackTrace(System.out);
242        }
243        return null;
244    }
245
246    public void loadUserLayerKML(String name, InputStream data, UserData ud) {
247        try {
248            String kmlData = "";
249
250            if (data != null) {
251                Writer writer = new StringWriter();
252
253                char[] buffer = new char[1024];
254                try {
255                    Reader reader = new BufferedReader(
256                            new InputStreamReader(data));
257                    int n;
258                    while ((n = reader.read(buffer)) != -1) {
259                        writer.write(buffer, 0, n);
260                    }
261                } finally {
262                    data.close();
263                }
264                kmlData = writer.toString();
265            }
266
267            loadUserLayerKML(name, kmlData.getBytes(), ud);
268
269        } catch (Exception e) {
270            getMapComposer().showMessage("Unable to load your file. Please try again.");
271
272            System.out.println("unable to load user kml: ");
273            e.printStackTrace(System.out);
274        }
275    }
276
277    public void loadUserLayerKML(String name, byte[] kmldata, UserData ud) {
278        try {
279
280            String id = String.valueOf(System.currentTimeMillis());
281            String kmlpath = "/data/ala/runtime/output/layers/" + id + "/";
282            File kmlfilepath = new File(kmlpath);
283            kmlfilepath.mkdirs();
284            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(kmlfilepath.getAbsolutePath() + "/" + name)));
285            String kmlstr = new String(kmldata);
286            out.write(kmlstr);
287            out.close();
288
289            MapComposer mc = getMapComposer();
290            layerName = (mc.getMapLayer(txtLayerName.getValue()) == null) ? txtLayerName.getValue() : mc.getNextAreaLayerName(txtLayerName.getValue());
291            String wkt = getKMLPolygonAsWKT(kmlstr);
292            MapLayer mapLayer = mc.addWKTLayer(wkt, layerName, txtLayerName.getValue());
293
294            ud.setUploadedTimeInMs(Long.parseLong(id));
295            ud.setType("kml");
296
297            String metadata = "";
298            metadata += "User uploaded KML area \n";
299            metadata += "Name: " + ud.getName() + " <br />\n";
300            metadata += "Filename: " + ud.getFilename() + " <br />\n";
301            metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
302
303            MapLayerMetadata mlmd = mapLayer.getMapLayerMetadata();
304            if (mlmd == null) {
305                mlmd = new MapLayerMetadata();
306            }
307            mlmd.setMoreInfo(metadata);
308            mapLayer.setMapLayerMetadata(mlmd);
309
310            if (mapLayer == null) {
311                logger.debug("The layer " + name + " couldnt be created");
312                mc.showMessage(mc.getLanguagePack().getLang("ext_layer_creation_failure"));
313            } else {
314                ok = true;
315                //this.layerName = mapLayer.getName();
316                //String kmlwkt = getKMLPolygonAsWKT(kmlstr);
317                //mapLayer.setWKT(kmlwkt);
318                mc.addUserDefinedLayerToMenu(mapLayer, true);
319            }
320        } catch (Exception e) {
321
322            getMapComposer().showMessage("Unable to load your file. Please try again.");
323
324            System.out.println("unable to load user kml: ");
325            e.printStackTrace(System.out);
326        }
327    }
328
329    private static String getKMLPolygonAsWKT(String kmldata) {
330        try {
331            Parser parser = new Parser(new KMLConfiguration());
332            SimpleFeature f = (SimpleFeature) parser.parse(new StringReader(kmldata));
333            Collection placemarks = (Collection) f.getAttribute("Feature");
334
335            Geometry g = null;
336            SimpleFeature sf = null;
337
338            //for <Placemark>
339            if (placemarks.size() > 0 && placemarks.size() > 0) {
340                sf = (SimpleFeature) placemarks.iterator().next();
341                g = (Geometry) sf.getAttribute("Geometry");
342            }
343
344            //for <Folder><Placemark>
345            if (g == null && sf != null) {
346                placemarks = (Collection) sf.getAttribute("Feature");
347                if (placemarks != null && placemarks.size() > 0) {
348                    g = (Geometry) ((SimpleFeature) placemarks.iterator().next()).getAttribute("Geometry");
349                }
350            }
351
352            if (g != null) {
353                WKTWriter wr = new WKTWriter();
354                String wkt = wr.write(g);
355                return wkt.replace(" (", "(").replace(", ", ",").replace(") ", ")");
356            }
357
358        } catch (Exception e) {
359            e.printStackTrace(System.out);
360        }
361
362        return null;
363    }
364}