PageRenderTime 58ms CodeModel.GetById 17ms app.highlight 34ms RepoModel.GetById 2ms app.codeStats 0ms

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

http://alageospatialportal.googlecode.com/
Java | 515 lines | 416 code | 79 blank | 20 comment | 52 complexity | 8326246832cefa7aaf0a722a6e7e54e6 MD5 | raw file
  1package org.ala.spatial.analysis.web;
  2
  3import au.org.emii.portal.composer.UtilityComposer;
  4import au.org.emii.portal.menu.MapLayer;
  5import au.org.emii.portal.menu.MapLayerMetadata;
  6import au.org.emii.portal.settings.SettingsSupplementary;
  7import au.org.emii.portal.util.LayerUtilities;
  8import au.org.emii.portal.wms.WMSStyle;
  9import java.net.URL;
 10import org.ala.logger.client.RemoteLogger;
 11import org.ala.spatial.util.CommonData;
 12import org.apache.commons.httpclient.HttpClient;
 13import org.apache.commons.httpclient.methods.GetMethod;
 14import org.zkoss.zk.ui.Executions;
 15import org.zkoss.zk.ui.event.Event;
 16import org.zkoss.zul.Filedownload;
 17import org.zkoss.zul.Textbox;
 18
 19/**
 20 *
 21 * @author ajay
 22 */
 23public class ImportAnalysisController extends UtilityComposer {
 24
 25    SettingsSupplementary settingsSupplementary;
 26    RemoteLogger remoteLogger;
 27    Textbox refNum;
 28    String pid;
 29    boolean isAloc = false;
 30    boolean isMaxent = false;
 31    boolean isSxS = false;
 32    boolean isGdm = false;
 33    boolean sxsSitesBySpecies = false;
 34    boolean sxsOccurrenceDensity = false;
 35    boolean sxsSpeciesDensity = false;
 36    String[] gdmEnvlist;
 37
 38    @Override
 39    public void afterCompose() {
 40        super.afterCompose();
 41    }
 42
 43    public void onClick$btnOk(Event event) {
 44        pid = refNum.getValue();
 45        pid = pid.trim();
 46
 47        if (getParametersAloc()) {
 48            isAloc = true;
 49            openProgressBarAloc();
 50            remoteLogger.logMapAnalysis("Import Classification", "Tool - Restore", "", "", "", pid, "classification", "IMPORTED");
 51        } else if (getParametersMaxent()) {
 52            isMaxent = true;
 53            openProgressBarMaxent();
 54            remoteLogger.logMapAnalysis("Import Prediction", "Tool - Restore", "", "", "", pid, "prediction", "IMPORTED");
 55        } else if (getParametersSxS()) {
 56            isSxS = true;
 57            openProgressBarSxS();
 58            remoteLogger.logMapAnalysis("Import Species to Grid", "Tool - Restore", "", "", "", pid, "species to grid", "IMPORTED");
 59        } else if (getParametersGdm()) {
 60            isGdm = true;
 61            openProgressBarGdm();
 62            remoteLogger.logMapAnalysis("Import GDM", "Tool - Restore", "", "", "", pid, "gdm", "IMPORTED");
 63        } else {
 64            getMapComposer().showMessage("Invalid reference number.");
 65        }
 66    }
 67
 68    public void onClick$btnCancel(Event event) {
 69        this.detach();
 70    }
 71
 72    boolean getParametersAloc() {
 73        String txt = get("inputs");
 74        try {
 75            int pos = 0;
 76            int p1 = txt.indexOf("pid:", pos);
 77            if (p1 < 0) {
 78                return false;
 79            }
 80            int p2 = txt.indexOf("gc:", pos);
 81            if (p2 < 0) {
 82                return false;
 83            }
 84            int p3 = txt.indexOf("area:", pos);
 85            int p4 = txt.indexOf("envlist:", pos);
 86            int p5 = txt.indexOf("pid:", p1 + 4);
 87            if (p5 < 0) {
 88                p5 = txt.length();
 89            }
 90
 91            pos = p5 - 5;
 92
 93            String pid = txt.substring(p1 + 4, p2).trim();
 94            String gc = txt.substring(p2 + 3, p3).trim();
 95            String area = txt.substring(p3 + 5, p4).trim();
 96            String envlist = txt.substring(p4 + 8, p5).trim();
 97
 98            //remove ';' from end
 99            if (gc.endsWith(";")) {
100                gc = gc.substring(0, gc.length() - 1);
101            }
102            if (area.endsWith(";")) {
103                area = area.substring(0, area.length() - 1);
104            }
105            if (envlist.endsWith(";")) {
106                envlist = envlist.substring(0, envlist.length() - 1);
107            }
108
109            System.out.println("got [" + pid + "][" + gc + "][" + area + "][" + envlist + "]");
110
111            //apply job input parameters to selection
112//            groupCount.setValue(Integer.parseInt(gc));
113//
114//            lbListLayers.clearSelection();
115//            lbListLayers.selectLayers(envlist.split(":"));
116
117            return true;
118        } catch (Exception e) {
119            e.printStackTrace();
120        }
121        return false;
122    }
123
124    String get(String type) {
125        try {
126            StringBuffer sbProcessUrl = new StringBuffer();
127            sbProcessUrl.append(CommonData.satServer + "/ws/jobs/").append(type).append("?pid=").append(pid);
128
129            HttpClient client = new HttpClient();
130            GetMethod get = new GetMethod(sbProcessUrl.toString());
131
132            get.addRequestHeader("Accept", "text/plain");
133
134            int result = client.executeMethod(get);
135            String slist = get.getResponseBodyAsString();
136
137            return slist;
138        } catch (Exception e) {
139            e.printStackTrace();
140        }
141        return "";
142    }
143
144    void openProgressBarAloc() {
145        ProgressWCController window = (ProgressWCController) Executions.createComponents("WEB-INF/zul/AnalysisProgress.zul", getMapComposer(), null);
146        window.parent = this;
147        window.start(pid, "Classification");
148        try {
149            window.doModal();
150
151        } catch (Exception e) {
152            e.printStackTrace();
153        }
154    }
155
156    public void loadMap(Event event) {
157        if (isAloc) {
158            loadMapAloc(event);
159        } else if (isMaxent) {
160            loadMapMaxent(event);
161        } else if (isSxS) {
162            loadMapSxS(event);
163        }
164    }
165
166    public void loadMapAloc(Event event) {
167        String layerLabel = "Classification - " + pid;
168
169        String mapurl = CommonData.geoServer + "/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:aloc_" + pid + "&FORMAT=image%2Fpng";
170        String legendurl = CommonData.geoServer
171                + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=10&HEIGHT=1"
172                + "&LAYER=ALA:aloc_" + pid;
173        System.out.println(legendurl);
174        getMapComposer().addWMSLayer("aloc_" + pid, layerLabel, mapurl, (float) 0.5, null, legendurl, LayerUtilities.ALOC, null, null);
175        MapLayer mapLayer = getMapComposer().getMapLayer("aloc_" + pid);
176        mapLayer.setData("pid", pid);
177        if (mapLayer != null) {
178            WMSStyle style = new WMSStyle();
179            style.setName("Default");
180            style.setDescription("Default style");
181            style.setTitle("Default");
182            style.setLegendUri(legendurl);
183
184            System.out.println("legend:" + legendurl);
185            mapLayer.addStyle(style);
186            mapLayer.setSelectedStyleIndex(1);
187
188            MapLayerMetadata md = mapLayer.getMapLayerMetadata();
189            if (md == null) {
190                md = new MapLayerMetadata();
191            }
192
193            String infoUrl = CommonData.satServer + "/output/layers/" + pid + "/metadata.html" + "\nClassification output\npid:" + pid;
194            md.setMoreInfo(infoUrl);
195            md.setId(Long.valueOf(pid));
196
197            getMapComposer().updateLayerControls();
198
199            try {
200                // set off the download as well
201                String fileUrl = CommonData.satServer + "/ws/download/" + pid;
202                Filedownload.save(new URL(fileUrl).openStream(), "application/zip", layerLabel.replaceAll(" ", "_") + ".zip"); // "ALA_Prediction_"+pid+".zip"
203            } catch (Exception ex) {
204                System.out.println("Error generating download for classification model:");
205                ex.printStackTrace(System.out);
206            }
207        }
208
209        this.detach();
210    }
211
212    double[] getExtents() {
213        double[] d = new double[6];
214        try {
215            StringBuffer sbProcessUrl = new StringBuffer();
216            sbProcessUrl.append(CommonData.satServer + "/output/aloc/" + pid + "/aloc.pngextents.txt");
217
218            HttpClient client = new HttpClient();
219            GetMethod get = new GetMethod(sbProcessUrl.toString());
220
221            get.addRequestHeader("Accept", "text/plain");
222
223            int result = client.executeMethod(get);
224            String slist = get.getResponseBodyAsString();
225            System.out.println("getExtents:" + slist);
226
227            String[] s = slist.split("\n");
228            for (int i = 0; i < 6 && i < s.length; i++) {
229                d[i] = Double.parseDouble(s[i]);
230            }
231        } catch (Exception e) {
232            e.printStackTrace();
233        }
234        return d;
235    }
236
237    String getJob(String type) {
238        try {
239            StringBuffer sbProcessUrl = new StringBuffer();
240            sbProcessUrl.append(CommonData.satServer + "/ws/jobs/").append(type).append("?pid=").append(pid);
241
242            System.out.println(sbProcessUrl.toString());
243            HttpClient client = new HttpClient();
244            GetMethod get = new GetMethod(sbProcessUrl.toString());
245
246            get.addRequestHeader("Accept", "text/plain");
247
248            int result = client.executeMethod(get);
249            String slist = get.getResponseBodyAsString();
250            System.out.println(slist);
251            return slist;
252        } catch (Exception e) {
253            e.printStackTrace();
254        }
255        return "";
256    }
257
258    void openProgressBarMaxent() {
259        ProgressWCController window = (ProgressWCController) Executions.createComponents("WEB-INF/zul/AnalysisProgress.zul", getMapComposer(), null);
260        window.parent = this;
261        window.start(pid, "Prediction");
262        try {
263            window.doModal();
264        } catch (Exception e) {
265            e.printStackTrace();
266        }
267    }
268
269    boolean getParametersMaxent() {
270        String txt = get("inputs");
271        try {
272            int pos = 0;
273            int p1 = txt.indexOf("pid:", pos);
274            if (p1 < 0) {
275                return false;
276            }
277            int p2 = txt.indexOf("taxonid:", pos);
278            if (p2 < 0) {
279                return false;
280            }
281
282            return true;
283        } catch (Exception e) {
284            e.printStackTrace();
285        }
286        return false;
287    }
288
289    boolean getParametersSxS() {
290        String txt = get("inputs");
291        try {
292            int pos = 0;
293            int p1 = txt.indexOf("pid:", pos);
294            if (p1 < 0) {
295                return false;
296            }
297            int p2 = txt.indexOf("gridsize:", pos);
298            if (p2 < 0) {
299                return false;
300            }
301
302            if (txt.indexOf("sitesbyspecies") > 0) {
303                sxsSitesBySpecies = true;
304            }
305            if (txt.indexOf("occurrencedensity") > 0) {
306                sxsOccurrenceDensity = true;
307            }
308            if (txt.indexOf("speciesdensity") > 0) {
309                sxsSpeciesDensity = true;
310            }
311
312
313            return true;
314        } catch (Exception e) {
315            e.printStackTrace();
316        }
317        return false;
318    }
319
320    void openProgressBarSxS() {
321        ProgressWCController window = (ProgressWCController) Executions.createComponents("WEB-INF/zul/AnalysisProgress.zul", getMapComposer(), null);
322        window.parent = this;
323        window.start(pid, "Points to Grid");        
324        try {
325            window.doModal();
326        } catch (Exception e) {
327            e.printStackTrace();
328        }
329    }
330
331    public void loadMapMaxent(Event event) {
332
333        String mapurl = CommonData.geoServer + "/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:species_" + pid + "&styles=alastyles&FORMAT=image%2Fpng";
334
335        String legendurl = CommonData.geoServer
336                + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=10&HEIGHT=1"
337                + "&LAYER=ALA:species_" + pid
338                + "&STYLE=alastyles";
339
340        System.out.println(legendurl);
341
342        //get job inputs
343        String speciesName = "";
344        try {
345            for (String s : getJob("inputs").split(";")) {
346                if (s.startsWith("scientificName")) {
347                    speciesName = s.split(":")[1];
348                    if (speciesName != null && speciesName.length() > 1) {
349                        speciesName = speciesName.substring(0, 1).toUpperCase() + speciesName.substring(1);
350                    }
351                    break;
352                }
353            }
354        } catch (Exception e) {
355            e.printStackTrace();
356        }
357
358        //taxon = "species";
359
360
361        String layername = "Maxent - " + pid;
362        getMapComposer().addWMSLayer("species_" + pid, layername, mapurl, (float) 0.5, null, legendurl, LayerUtilities.MAXENT, null, null);
363        MapLayer ml = getMapComposer().getMapLayer("species_" + pid);
364        ml.setData("pid", pid);
365        String infoUrl = CommonData.satServer + "/output/maxent/" + pid + "/species.html";
366        MapLayerMetadata md = ml.getMapLayerMetadata();
367        if (md == null) {
368            md = new MapLayerMetadata();
369            ml.setMapLayerMetadata(md);
370        }
371        md.setMoreInfo(infoUrl + "\nMaxent Output\npid:" + pid);
372        md.setId(Long.valueOf(pid));
373
374        try {
375            // set off the download as well
376            String fileUrl = CommonData.satServer + "/ws/download/" + pid;
377            Filedownload.save(new URL(fileUrl).openStream(), "application/zip", layername.replaceAll(" ", "_") + ".zip"); // "ALA_Prediction_"+pid+".zip"
378        } catch (Exception ex) {
379            System.out.println("Error generating download for prediction model:");
380            ex.printStackTrace(System.out);
381        }
382
383        this.detach();
384
385        //getMapComposer().showMessage("Reference number to retrieve results: " + pid);
386
387        //showInfoWindow("/output/maxent/" + pid + "/species.html");
388    }
389
390    private void loadMapSxS(Event event) {
391        try {
392            if (sxsOccurrenceDensity) {
393                String mapurl = CommonData.geoServer + "/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:odensity_" + pid + "&styles=odensity_" + pid + "&FORMAT=image%2Fpng";
394                String legendurl = CommonData.geoServer
395                        + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=10&HEIGHT=1"
396                        + "&LAYER=ALA:odensity_" + pid
397                        + "&STYLE=odensity_" + pid;
398
399                System.out.println(legendurl);
400
401                String layername = getMapComposer().getNextAreaLayerName("Occurrence Density");
402                getMapComposer().addWMSLayer(pid + "_odensity", layername, mapurl, (float) 0.5, null, legendurl, LayerUtilities.ODENSITY, null, null);
403                MapLayer ml = getMapComposer().getMapLayer(pid + "_odensity");
404                ml.setData("pid", pid + "_odensity");
405                String infoUrl = CommonData.satServer + "/output/sitesbyspecies/" + pid + "/odensity_metadata.html";
406                MapLayerMetadata md = ml.getMapLayerMetadata();
407                if (md == null) {
408                    md = new MapLayerMetadata();
409                    ml.setMapLayerMetadata(md);
410                }
411                md.setMoreInfo(infoUrl + "\nOccurrence Density\npid:" + pid);
412                md.setId(Long.valueOf(pid));
413            }
414
415            if (sxsSpeciesDensity) {
416                String mapurl = CommonData.geoServer + "/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:srichness_" + pid + "&styles=srichness_" + pid + "&FORMAT=image%2Fpng";
417                String legendurl = CommonData.geoServer
418                        + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=10&HEIGHT=1"
419                        + "&LAYER=ALA:srichness_" + pid
420                        + "&STYLE=srichness_" + pid;
421
422                System.out.println(legendurl);
423
424//                String layername = tToolName.getValue();
425                String layername = getMapComposer().getNextAreaLayerName("Species Richness");
426                getMapComposer().addWMSLayer(pid + "_srichness", layername, mapurl, (float) 0.5, null, legendurl, LayerUtilities.SRICHNESS, null, null);
427                MapLayer ml = getMapComposer().getMapLayer(pid + "_srichness");
428                ml.setData("pid", pid + "_srichness");
429                String infoUrl = CommonData.satServer + "/output/sitesbyspecies/" + pid + "/srichness_metadata.html";
430                MapLayerMetadata md = ml.getMapLayerMetadata();
431                if (md == null) {
432                    md = new MapLayerMetadata();
433                    ml.setMapLayerMetadata(md);
434                }
435                md.setMoreInfo(infoUrl + "\nSpecies Richness\npid:" + pid);
436                md.setId(Long.valueOf(pid));
437            }
438
439            // set off the download as well
440            String fileUrl = CommonData.satServer + "/ws/download/" + pid;
441            Filedownload.save(new URL(fileUrl).openStream(), "application/zip", "sites_by_species.zip");
442        } catch (Exception ex) {
443            System.out.println("Error generating download for prediction model:");
444            ex.printStackTrace(System.out);
445        }
446
447        this.detach();
448    }
449
450    boolean getParametersGdm() {
451        try {
452            StringBuffer sbProcessUrl = new StringBuffer();
453            //TODO: analysis output url into config
454            sbProcessUrl.append(CommonData.satServer.replace("/alaspatial", "") + "/output/gdm/").append(pid).append("/ala.properties");
455
456            HttpClient client = new HttpClient();
457            GetMethod get = new GetMethod(sbProcessUrl.toString());
458
459            get.addRequestHeader("Accept", "text/plain");
460
461            int result = client.executeMethod(get);
462
463            if (result == 200) {
464                String slist = get.getResponseBodyAsString();
465                for (String row : slist.split("\n")) {
466                    if (row.startsWith("envlist")) {
467                        gdmEnvlist = row.replace("envlist=", "").split("\\\\:");
468                    }
469                }
470                return true;
471            }
472        } catch (Exception e) {
473            e.printStackTrace();
474        }
475        return false;
476    }
477
478    void openProgressBarGdm() {
479        String[] envlist = gdmEnvlist;
480
481        for (String env : envlist) {
482            String mapurl = CommonData.geoServer + "/wms?service=WMS&version=1.1.0&request=GetMap&layers=ALA:gdm_" + env + "Tran_" + pid + "&styles=alastyles&FORMAT=image%2Fpng";
483
484            String legendurl = CommonData.geoServer
485                    + "/wms?REQUEST=GetLegendGraphic&VERSION=1.0.0&FORMAT=image/png&WIDTH=10&HEIGHT=1"
486                    + "&LAYER=ALA:gdm_" + env + "Tran_" + pid
487                    + "&STYLE=alastyles";
488
489            System.out.println(legendurl);
490
491            String layername = "Tranformed " + CommonData.getLayerDisplayName(env);
492            //System.out.println("Converting '" + env + "' to '" + layername.substring(10) + "' (" + CommonData.getFacetLayerDisplayName(CommonData.getLayerFacetName(env)) + ")");
493            getMapComposer().addWMSLayer(pid + "_" + env, layername, mapurl, (float) 0.5, null, legendurl, LayerUtilities.GDM, null, null);
494            MapLayer ml = getMapComposer().getMapLayer(pid + "_" + env);
495            ml.setData("pid", pid + "_" + env);
496            String infoUrl = CommonData.satServer + "/output/gdm/" + pid + "/gdm.html";
497            MapLayerMetadata md = ml.getMapLayerMetadata();
498            if (md == null) {
499                md = new MapLayerMetadata();
500                ml.setMapLayerMetadata(md);
501            }
502            md.setMoreInfo(infoUrl + "\nGDM Output\npid:" + pid);
503            md.setId(Long.valueOf(pid));
504        }
505
506        String fileUrl = CommonData.satServer + "/ws/download/" + pid;
507        try {
508            Filedownload.save(new URL(fileUrl).openStream(), "application/zip", "gdm_" + pid + ".zip"); // "ALA_Prediction_"+pid+".zip"
509        } catch (Exception e) {
510            e.printStackTrace();
511        }
512
513         this.detach();
514    }
515}