PageRenderTime 35ms CodeModel.GetById 10ms app.highlight 21ms RepoModel.GetById 1ms app.codeStats 0ms

/alaspatial/src/main/java/org/ala/spatial/web/services/DownloadController.java

http://alageospatialportal.googlecode.com/
Java | 394 lines | 267 code | 77 blank | 50 comment | 61 complexity | ae78788a531032aeaafcabad0e8e3d21 MD5 | raw file
  1/**
  2 * ************************************************************************
  3 * Copyright (C) 2010 Atlas of Living Australia All Rights Reserved.
  4 *
  5 * The contents of this file are subject to the Mozilla Public License Version
  6 * 1.1 (the "License"); you may not use this file except in compliance with the
  7 * License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
  8 *
  9 * Software distributed under the License is distributed on an "AS IS" basis,
 10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 11 * the specific language governing rights and limitations under the License.
 12 * *************************************************************************
 13 */
 14package org.ala.spatial.web.services;
 15
 16import java.io.*;
 17import java.util.Iterator;
 18import javax.servlet.http.HttpServletResponse;
 19import javax.swing.filechooser.FileNameExtensionFilter;
 20import org.ala.spatial.util.AlaspatialProperties;
 21import org.ala.spatial.util.Zipper;
 22import org.apache.commons.io.FileUtils;
 23import org.apache.commons.io.IOCase;
 24import org.apache.commons.io.filefilter.DirectoryFileFilter;
 25import org.apache.commons.io.filefilter.SuffixFileFilter;
 26import org.springframework.stereotype.Controller;
 27import org.springframework.util.FileCopyUtils;
 28import org.springframework.web.bind.annotation.PathVariable;
 29import org.springframework.web.bind.annotation.RequestMapping;
 30import org.springframework.web.bind.annotation.RequestMethod;
 31import org.springframework.web.bind.annotation.ResponseBody;
 32
 33/**
 34 *
 35 * @author ajay
 36 */
 37@Controller
 38@RequestMapping("/ws/download/")
 39public class DownloadController {
 40
 41    @RequestMapping(value = "/session/{sessionid}", method = RequestMethod.GET)
 42    @ResponseBody
 43    public String downloadSessionUrl(@PathVariable String sessionid, HttpServletResponse response) {
 44        try {
 45            
 46            String basedir = AlaspatialProperties.getBaseOutputDir() + File.separator + "output" + File.separator;
 47            String sessiondir = basedir + "session" + File.separator + sessionid;
 48            File sDir = new File(sessiondir);
 49            
 50            if (sDir.exists() && sDir.isDirectory()) {
 51                StringBuffer sbSession = new StringBuffer();
 52                sbSession.append("[InternetShortcut]").append("\n");
 53                sbSession.append("URL=").append(AlaspatialProperties.getBaseOutputURL());
 54                sbSession.append("?ss=").append(sessionid).append("\n");
 55                
 56                response.setContentType("application/internet-shortcut");
 57                response.setContentLength(safeLongToInt(sbSession.length()));
 58                response.setHeader("Content-Disposition", "attachment; filename=\"ALA_Spatial_Portal_Session_" + sessionid + ".url\"");
 59
 60                FileCopyUtils.copy(sbSession.toString(), response.getWriter());
 61
 62                return null;
 63            }
 64        } catch (Exception e) {
 65            System.out.println("Could not find session directory");            
 66        }
 67        
 68        return ""; 
 69    }
 70    
 71    @RequestMapping(value = "/{pid}", method = RequestMethod.GET)
 72    @ResponseBody
 73    public String download(@PathVariable String pid, HttpServletResponse response) {
 74        try {
 75
 76            File dir = findFile(pid);
 77
 78            if (dir != null) {
 79
 80                String parentName = "ALA_";
 81                String parentPath = dir.getParent().substring(dir.getParent().lastIndexOf("/") + 1);
 82
 83                String zipfile = dir.getParent() + "/" + pid + ".zip";
 84
 85                if ("maxent".equals(parentPath)) {
 86                    fixMaxentFiles(pid, dir);
 87                    Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile);
 88                } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) {
 89                    fixAlocFiles(pid, dir);
 90                    Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile);
 91                }else if ("gdm".equals(parentPath)) {
 92                    fixGdmFiles(pid, dir);
 93                    Zipper.zipDirectory(dir.getParent()+"/temp/"+pid, zipfile);
 94                } else {
 95                    Zipper.zipDirectory(dir.getAbsolutePath(), zipfile);
 96                }
 97
 98
 99
100                System.out.println("Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile);
101                //return "Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile;
102
103                if ("maxent".equals(parentPath)) {
104                    parentName = "ALA_Prediction_";
105                } else if ("sampling".equals(parentPath)) {
106                    parentName = "ALA_Species_Samples_";
107                } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) {
108                    parentName = "ALA_Classification_";
109                } else if ("gdm".equals(parentPath)) {
110                    parentName = "ALA_GDM_";
111                } else if ("filtering".equals(parentPath)) {
112                    parentName = "ALA_EnvFilter_";
113                } else if ("sitesbyspecies".equals(parentPath)) {
114                    parentName = "ALA_SitesBySpecies_";
115                }
116
117                File file = new File(zipfile);
118                response.setContentType("application/zip");
119                response.setContentLength(safeLongToInt(file.length()));
120                response.setHeader("Content-Disposition", "attachment; filename=\"" + parentName + pid + ".zip\"");
121
122                FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());
123
124                return null;
125
126            } else {
127                System.out.println("Could not find session data");
128                return "Could not find session data";
129            }
130
131        } catch (Exception e) {
132            System.out.println("Unable to download:");
133            e.printStackTrace(System.out);
134        }
135
136        return "";
137    }
138
139    private File findFile(String pid) {
140        try {
141            System.out.println("Looking for: " + pid + " to downloadd");
142
143            // the 'pid's are unique, so lets figure out
144            // which directory they live under.
145
146            String basedir = AlaspatialProperties.getBaseOutputDir() + File.separator + "output" + File.separator;
147            File baseDir = new File(basedir);
148            FilenameFilter ff = DirectoryFileFilter.DIRECTORY;
149            File[] files = baseDir.listFiles(ff);
150            for (int i = 0; i < files.length; i++) {
151                File f = files[i];
152                if (f.isDirectory() && !f.getName().equalsIgnoreCase("layers")) {
153                    if (f.getName().equalsIgnoreCase(pid)) {
154                        return f;
155                    } else {
156                        File[] files2 = f.listFiles(ff);
157                        for (int j = 0; j < files2.length; j++) {
158                            File f2 = files2[j];
159                            if (f2.getName().equalsIgnoreCase(pid)) {
160                                return f2;
161                            }
162                        }
163                    }
164                }
165            }
166
167        } catch (Exception e) {
168            System.out.println("Error finding session data:");
169            e.printStackTrace(System.out);
170        }
171
172        return null;
173    }
174
175    private static void fixMaxentFiles(String pid, File dir) {
176        try {
177            File tmpdir = new File(dir.getParent() + "/temp/" + pid);
178            //FileCopyUtils.copy(new FileInputStream(dir), new FileOutputStream(tmpdir));
179            FileUtils.copyDirectory(dir, tmpdir);
180
181            //File grd = new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd");
182            //File grdnew = new File(tmpdir.getAbsolutePath() + "/prediction.grd");
183
184            //File gri = new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri");
185            //File grinew = new File(tmpdir.getAbsolutePath() + "/prediction.gri");
186
187            File rsp = new File(tmpdir.getAbsolutePath() + "/removedSpecies.txt");
188            File rspnew = new File(tmpdir.getAbsolutePath() + "/prediction_removedSpecies.txt");
189
190            File msp = new File(tmpdir.getAbsolutePath() + "/maskedOutSensitiveSpecies.txt");
191            File mspnew = new File(tmpdir.getAbsolutePath() + "/prediction_maskedOutSensitiveSpecies.txt");
192
193            //grd.renameTo(grdnew);
194            //gri.renameTo(grinew);
195            rsp.renameTo(rspnew);
196            msp.renameTo(mspnew);
197
198            (new File(tmpdir.getAbsolutePath() + "/species.zip")).delete();
199            (new File(tmpdir.getAbsolutePath() + "/species.bat")).delete();
200            (new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd")).delete();
201            (new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri")).delete();
202
203        } catch (Exception e) {
204            System.out.println("Unable to fix Prediction files");
205            e.printStackTrace(System.out);
206        }
207    }
208
209    private static void fixAlocFiles(String pid, File dir) {
210        try {
211            File tmpdir = new File(dir.getParent() + "/temp/" + pid);
212            //FileCopyUtils.copy(new FileInputStream(dir), new FileOutputStream(tmpdir));
213            FileUtils.copyDirectory(dir, tmpdir);
214
215            //File grd = new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd");
216            //File grdnew = new File(tmpdir.getAbsolutePath() + "/classfication.grd");
217
218            //File gri = new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri");
219            //File grinew = new File(tmpdir.getAbsolutePath() + "/classfication.gri");
220
221            File asc = new File(tmpdir.getAbsolutePath() + "/" + pid + ".asc");
222            File ascnew = new File(tmpdir.getAbsolutePath() + "/classfication.asc");
223
224            File prj = new File(tmpdir.getAbsolutePath() + "/" + pid + ".prj");
225            File prjnew = new File(tmpdir.getAbsolutePath() + "/classfication.prj");
226
227            File png = new File(tmpdir.getAbsolutePath() + "/aloc.png");
228            File pngnew = new File(tmpdir.getAbsolutePath() + "/classfication.png");
229
230            File pgw = new File(tmpdir.getAbsolutePath() + "/aloc.pgw");
231            File pgwnew = new File(tmpdir.getAbsolutePath() + "/classfication.pgw");
232
233            File log = new File(tmpdir.getAbsolutePath() + "/aloc.log");
234            File lognew = new File(tmpdir.getAbsolutePath() + "/classfication.log");
235
236            //grd.renameTo(grdnew);
237            //gri.renameTo(grinew);
238            asc.renameTo(ascnew);
239            prj.renameTo(prjnew);
240            png.renameTo(pngnew);
241            pgw.renameTo(pgwnew);
242            log.renameTo(lognew);
243
244            (new File(tmpdir.getAbsolutePath() + "/" + pid + ".asc.zip")).delete();
245            (new File(tmpdir.getAbsolutePath() + "/" + pid + ".sld")).delete();
246            (new File(tmpdir.getAbsolutePath() + "/aloc.pngextents.txt")).delete();
247            (new File(tmpdir.getAbsolutePath() + "/aloc.prj")).delete();
248            (new File(tmpdir.getAbsolutePath() + "/t_aloc.tif")).delete();
249            (new File(tmpdir.getAbsolutePath() + "/t_aloc.png")).delete();
250            (new File(tmpdir.getAbsolutePath() + "/" + pid + ".grd")).delete();
251            (new File(tmpdir.getAbsolutePath() + "/" + pid + ".gri")).delete();
252
253        } catch (Exception e) {
254            System.out.println("Unable to fix Classification files");
255            e.printStackTrace(System.out);
256        }
257    }
258
259    private static void fixGdmFiles(String pid, File dir) {
260        try {
261            File tmpdir = new File(dir.getParent() + "/temp/" + pid);
262            //FileCopyUtils.copy(new FileInputStream(dir), new FileOutputStream(tmpdir));
263            FileUtils.copyDirectory(dir, tmpdir);
264
265            //File rsp = new File(tmpdir.getAbsolutePath() + "/removedSpecies.txt");
266            //File rspnew = new File(tmpdir.getAbsolutePath() + "/prediction_removedSpecies.txt");
267
268            //File msp = new File(tmpdir.getAbsolutePath() + "/maskedOutSensitiveSpecies.txt");
269            //File mspnew = new File(tmpdir.getAbsolutePath() + "/prediction_maskedOutSensitiveSpecies.txt");
270
271            //rsp.renameTo(rspnew);
272            //msp.renameTo(mspnew);
273
274            //(new File(tmpdir.getAbsolutePath() + "/species.zip")).delete();
275
276            FilenameFilter ff = new SuffixFileFilter(".grd");
277            File[] files = tmpdir.listFiles(ff);
278            for (int i = 0; i < files.length; i++) {
279                File f = files[i];
280                if (!f.getName().startsWith("domain")) {
281                    f.delete();
282                }
283            }
284
285        } catch (Exception e) {
286            System.out.println("Unable to fix Prediction files");
287            e.printStackTrace(System.out);
288        }
289    }
290
291    private static File sfindFile(String pid) {
292        try {
293            System.out.println("Looking for: " + pid + " to download");
294
295            // the 'pid's are unique, so lets figure out
296            // which directory they live under.
297
298            String basedir = "/data/ala/runtime/output" + File.separator;
299            File baseDir = new File(basedir);
300            FilenameFilter ff = DirectoryFileFilter.DIRECTORY;
301            File[] files = baseDir.listFiles(ff);
302            for (int i = 0; i < files.length; i++) {
303                File f = files[i];
304                if (f.isDirectory() && !f.getName().equalsIgnoreCase("layers")) {
305                    if (f.getName().equalsIgnoreCase(pid)) {
306                        return f;
307                    } else {
308                        File[] files2 = f.listFiles(ff);
309                        for (int j = 0; j < files2.length; j++) {
310                            File f2 = files2[j];
311                            if (f2.getName().equalsIgnoreCase(pid)) {
312                                return f2;
313                            }
314                        }
315                    }
316                }
317            }
318
319        } catch (Exception e) {
320            System.out.println("Error finding session data:");
321            e.printStackTrace(System.out);
322        }
323
324        return null;
325    }
326
327    private int safeLongToInt(long l) {
328        if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
329            throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
330        }
331        return (int) l;
332    }
333
334    public static void main(String[] args) {
335
336        // maxent - 1323641423144
337        // aloc   - 1323844048457
338
339        String pid = "1323844048457";
340
341        try {
342            File dir = sfindFile(pid);
343
344            if (dir != null) {
345                //System.out.println("Found session data: " + dir.getAbsolutePath());
346                //return "Found session data: " + dir.getAbsolutePath();
347
348                String parentName = "ALA_";
349                String parentPath = dir.getParent().substring(dir.getParent().lastIndexOf("/") + 1);
350
351                String zipfile = dir.getParent() + "/" + pid + ".zip";
352
353                if ("maxent".equals(parentPath)) {
354                    fixMaxentFiles(pid, dir);
355                    Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile);
356                } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) {
357                    fixAlocFiles(pid, dir);
358                    Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile);
359                } else {
360                    Zipper.zipDirectory(dir.getAbsolutePath(), zipfile);
361                }
362
363
364
365                System.out.println("Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile);
366                //return "Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile;
367
368                if ("maxent".equals(parentPath)) {
369                    parentName = "ALA_Prediction_";
370                } else if ("sampling".equals(parentPath)) {
371                    parentName = "ALA_Species_Samples_";
372                } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) {
373                    parentName = "ALA_Classification_";
374                } else if ("gdm".equals(parentPath)) {
375                    parentName = "ALA_GDM_";
376                } else if ("filtering".equals(parentPath)) {
377                    parentName = "ALA_EnvFilter_";
378                } else if ("sitesbyspecies".equals(parentPath)) {
379                    parentName = "ALA_SitesBySpecies_";
380                }
381
382                File file = new File(zipfile);
383
384                System.out.println("File generated: " + file.getAbsolutePath());
385
386            } else {
387                System.out.println("Could not find session data");
388                //return "Could not find session data";
389            }
390        } catch (Exception e) {
391            e.printStackTrace(System.out);
392        }
393    }
394}