ServerAction.java
上传用户:zhengdagz
上传日期:2014-03-06
资源大小:1956k
文件大小:10k
源码类别:

xml/soap/webservice

开发平台:

Java

  1. /*
  2.  * $Id: ServerAction.java,v 1.4 2005/10/13 08:59:55 kleopatra Exp $
  3.  *
  4.  * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
  5.  * Santa Clara, California 95054, U.S.A. All rights reserved.
  6.  *
  7.  * This library is free software; you can redistribute it and/or
  8.  * modify it under the terms of the GNU Lesser General Public
  9.  * License as published by the Free Software Foundation; either
  10.  * version 2.1 of the License, or (at your option) any later version.
  11.  * 
  12.  * This library is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15.  * Lesser General Public License for more details.
  16.  * 
  17.  * You should have received a copy of the GNU Lesser General Public
  18.  * License along with this library; if not, write to the Free Software
  19.  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  20.  */
  21. package org.jdesktop.swingx.action;
  22. import java.awt.event.ActionEvent;
  23. import java.io.BufferedReader;
  24. import java.io.ByteArrayOutputStream;
  25. import java.io.InputStreamReader;
  26. import java.io.IOException;
  27. import java.io.PrintWriter;
  28. import java.io.UnsupportedEncodingException;
  29. import java.net.MalformedURLException;
  30. import java.net.HttpURLConnection;
  31. import java.net.UnknownHostException;
  32. import java.net.URL;
  33. import java.net.URLConnection;
  34. import java.security.AccessControlException;
  35. import java.util.Map;
  36. import java.util.HashMap;
  37. import java.util.Iterator;
  38. import java.util.Set;
  39. import javax.swing.AbstractAction;
  40. import javax.swing.Action;
  41. import javax.swing.Icon;
  42. //import org.jdesktop.swing.Application;
  43. /**
  44.  * An action which will invoke an http POST operation.
  45.  *
  46.  * @author Mark Davidson
  47.  */
  48. public class ServerAction extends AbstractAction {
  49.     // Server action support
  50.     private static final String PARAMS = "action-params";
  51.     private static final String HEADERS = "action-headers";
  52.     private static final String URL = "action-url";
  53.     private static final String URL_CACHE = "_URL-CACHE__";
  54.     public ServerAction() {
  55. this("action");
  56.     }
  57.     public ServerAction(String name) {
  58. super(name);
  59.     }
  60.     /**
  61.      * @param name display name of the action
  62.      * @param command the value of the action command key
  63.      */
  64.     public ServerAction(String name, String command) {
  65. this(name, command, null);
  66.     }
  67.     public ServerAction(String name, Icon icon) {
  68. super(name, icon);
  69.     }
  70.     /**
  71.      * @param name display name of the action
  72.      * @param command the value of the action command key
  73.      * @param icon icon to display
  74.      */
  75.     public ServerAction(String name, String command, Icon icon) {
  76. super(name, icon);
  77. putValue(Action.ACTION_COMMAND_KEY, command);
  78.     }
  79.     /**
  80.      * Set the url for the action.
  81.      * <p>
  82.      * @param url a string representation of the url
  83.      */
  84.     public void setURL(String url) {
  85. putValue(URL, url);
  86. putValue(URL_CACHE, null);
  87.     }
  88.     public String getURL() {
  89. return (String)getValue(URL);
  90.     }
  91.     private Map getParams() {
  92. return (Map)getValue(PARAMS);
  93.     }
  94.     private void setParams(Map params) {
  95. putValue(PARAMS, params);
  96.     }
  97.     /**
  98.      * Adds a name value pair which represents a url parameter in an http
  99.      * POST request.
  100.      */
  101.     public void addParam(String name, String value) {
  102. Map params = getParams();
  103. if (params == null) {
  104.     params = new HashMap();
  105.     setParams(params);
  106. }
  107. params.put(name, value);
  108.     }
  109.     /**
  110.      * Return a parameter value corresponding to name or null if it doesn't exist.
  111.      */
  112.     public String getParamValue(String name) {
  113. Map params = getParams();
  114. return params == null ? null : (String)params.get(name);
  115.     }
  116.     /**
  117.      * Return a set of parameter names or null if there are no params
  118.      */
  119.     public Set getParamNames() {
  120. Map params = getParams();
  121. return params == null ? null : params.keySet();
  122.     }
  123.     private Map getHeaders() {
  124. return (Map)getValue(HEADERS);
  125.     }
  126.     private void setHeaders(Map headers) {
  127. putValue(HEADERS, headers);
  128.     }
  129.     /**
  130.      * Adds a name value pair which represents a url connection request property.
  131.      * For example, name could be "Content-Type" and the value could be
  132.      * "application/x-www-form-urlencoded"
  133.      */
  134.     public void addHeader(String name, String value) {
  135. Map map = getHeaders();
  136. if (map != null) {
  137.     map = new HashMap();
  138.     setHeaders(map);
  139. }
  140. map.put(name, value);
  141.     }
  142.     /**
  143.      * Return a header value corresponding to name or null if it doesn't exist.
  144.      */
  145.     public String getHeaderValue(String name) {
  146. Map headers = getHeaders();
  147. return headers == null ? null : (String)headers.get(name);
  148.     }
  149.     /**
  150.      * Return a set of parameter names or null if there are no params
  151.      */
  152.     public Set getHeaderNames() {
  153. Map headers = getHeaders();
  154. return headers == null ? null : headers.keySet();
  155.     }
  156.     /**
  157.      * Invokes the server operation when the action has been invoked.
  158.      */
  159.     public void actionPerformed(ActionEvent evt) {
  160. URL execURL = (URL)getValue(URL_CACHE);
  161. if (execURL == null && !"".equals(getURL())) {
  162.     try {
  163. String url = getURL();
  164. if (url.startsWith("http")) {
  165.     execURL = new URL(url);
  166. } else {
  167. }
  168. if (execURL == null) {
  169.     // XXX TODO: send a message
  170.     return;
  171. } else {
  172.     // Cache this value.
  173.     putValue(URL_CACHE, execURL);
  174. }
  175.     } catch (MalformedURLException ex) {
  176. ex.printStackTrace();
  177.     }
  178. }
  179. try {
  180.     URLConnection uc = execURL.openConnection();
  181.     // Get all the header name/value pairs ans set the request headers
  182.     Set headerNames = getHeaderNames();
  183.     if (headerNames != null && !headerNames.isEmpty()) {
  184. Iterator iter = headerNames.iterator();
  185. while (iter.hasNext()) {
  186.     String name = (String)iter.next();
  187.     uc.setRequestProperty(name, getHeaderValue(name));
  188. }
  189.     }
  190.     uc.setUseCaches(false);
  191.     uc.setDoOutput(true);
  192.     ByteArrayOutputStream byteStream = new ByteArrayOutputStream(512);
  193.     PrintWriter out = new PrintWriter(byteStream, true);
  194.     out.print(getPostData());
  195.     out.flush();
  196.     // POST requests must have a content-length.
  197.     String length = String.valueOf(byteStream.size());
  198.     uc.setRequestProperty("Content-length", length);
  199.     // Write POST data to real output stream.
  200.     byteStream.writeTo(uc.getOutputStream());
  201.     BufferedReader buf = null;
  202.     if (uc instanceof HttpURLConnection) {
  203. HttpURLConnection huc = (HttpURLConnection)uc;
  204. int code = huc.getResponseCode();
  205. String message = huc.getResponseMessage();
  206. // Handle the result.
  207. if (code < 400) {
  208.     // action succeeded send to status bar
  209.     // XXX TODO: setStatusMessage(createMessage(code, message));
  210.     // Format the response
  211.     // TODO: This should load asychnonously
  212.     buf = new BufferedReader(new InputStreamReader(uc.getInputStream()));
  213. } else {
  214.     // action has failed show dialog
  215.     // XXX TODO: setStatusMessage(createMessage(code, message));
  216.     buf = new BufferedReader(new InputStreamReader(huc.getErrorStream()));
  217. }
  218. String line;
  219. StringBuffer buffer = new StringBuffer();
  220. while ((line = buf.readLine()) != null) {
  221.             // RG: Fix for J2SE 5.0; Can't cascade append() calls because
  222.             // return type in StringBuffer and AbstractStringBuilder are different
  223.     buffer.append(line);
  224.             buffer.append('n');
  225. }
  226. if (Debug.debug) {
  227.     // XXX So now that we have results in the StringBuffer, we should do something
  228.     // with it.
  229.     System.out.println(buffer.toString());
  230. }
  231.     }
  232. } catch (UnknownHostException uhe) {
  233.     Debug.printException("UnknownHostException detected. Could it be a proxy issue?n" +
  234.  uhe.getMessage(), uhe);
  235. } catch (AccessControlException aex) {
  236.     Debug.printException("AccessControlException detectedn" +
  237.     aex.getMessage(), aex);
  238. } catch (IOException ex) {
  239.     Debug.printException("IOException detectedn" +
  240.  ex.getMessage(), ex);
  241. }
  242.     }
  243.     /**
  244.      * Retrieves a string which represents the parameter data for a server action.
  245.      * @return a string of name value pairs prefixed by a '?' and delimited by an '&'
  246.      */
  247.     private String getPostData() {
  248. // Write the data into local buffer
  249. StringBuffer postData = new StringBuffer();
  250. // TODO: the action should be configured to retrieve the data.
  251. // Get all the param name/value pairs and build the data string
  252. Set paramNames = getParamNames();
  253. if (paramNames != null && !paramNames.isEmpty()) {
  254.     Iterator iter = paramNames.iterator();
  255.         try {
  256.             while (iter.hasNext()) {
  257.                 String name = (String) iter.next();
  258.                 postData.append('&').append(name).append('=');
  259.                 postData.append(getParamValue(name));
  260.             }
  261.         }
  262.         catch (Exception ex) {  // RG: append(char) throws IOException in J2SE 5.0
  263.             /** @todo Log it */
  264.         }
  265.     // Replace the first & with a ?
  266.     postData.setCharAt(0, '?');
  267. }
  268. if (Debug.debug) {
  269.     System.out.println("ServerAction: POST data: " + postData.toString());
  270. }
  271. return postData.toString();
  272.     }
  273.     /**
  274.      * Creates a human readable message from the server code and message result.
  275.      * @param code an http error code.
  276.      * @param msg server message
  277.      */
  278.     private String createMessage(int code, String msg) {
  279. StringBuffer buffer = new StringBuffer("The action "");
  280. buffer.append(getValue(NAME));
  281. if (code < 400) {
  282.     buffer.append("" has succeeded ");
  283. } else {
  284.     buffer.append("" has failednPlease check the Java console for more details.n");
  285. }
  286.     // RG: Fix for J2SE 5.0; Can't cascade append() calls because
  287.     // return type in StringBuffer and AbstractStringBuilder are different
  288. buffer.append("nServer response:nCode: ");
  289.     buffer.append(code);
  290. buffer.append(" Message: ");
  291.     buffer.append(msg);
  292. return buffer.toString();
  293.     }
  294. }