View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.example.launcher;
8   
9   import java.net.URL;
10  import java.net.URLConnection;
11  import java.util.HashMap;
12  import java.util.Map;
13  
14  public class SimpleDownloadManager
15  {
16      private final static String URL_KEY = "url";
17  
18      /**
19  	 * 
20  	 */
21      public SimpleDownloadManager()
22      {
23      }
24  
25      /**
26       * Performs a HTTP GET or HTTP POST request and returns the contents.
27       * 
28       * @param data <code>Map</code> instance containing the URL (should start with
29       *            http://) and the method (GET or POST)
30       * @return The contents
31       */
32      public Object download(Object data)
33      {
34          String fileUrl = null;
35          Map<String, Object> response = new HashMap<String, Object>();
36  
37          if (data instanceof Map<?, ?>)
38          {
39              Map<?, ?> params = (Map<?, ?>) data;
40  
41              fileUrl = String.valueOf(params.get(URL_KEY));
42          }
43          else if (data instanceof String)
44          {
45              fileUrl = (String) data;
46          }
47  
48          if (fileUrl != null)
49          {
50              try
51              {
52                  URL url = new URL(fileUrl);
53                  URLConnection conn = url.openConnection();
54                  response.put("is", conn.getInputStream());
55                  response.put("filename", getFilenameFromUrl(fileUrl));
56              }
57              catch (Exception ex)
58              {
59                  response.put("error", "Error downloading " + fileUrl + " -> " + ex.getMessage());
60              }
61          }
62          else
63          {
64              response.put("error", "Not able to get URL to download");
65          }
66          return response;
67      }
68  
69      private String getFilenameFromUrl(String fileUrl)
70      {
71          if (fileUrl != null)
72          {
73              int i = fileUrl.lastIndexOf("/");
74              return fileUrl.substring(i + 1);
75          }
76          return null;
77      }
78  }