View Javadoc

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