View Javadoc
1   /**
2    * Copyright 2014 Internet2
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  /*
17   * $Header: /home/hagleyj/i2mi/grouper-misc/grouperClient/src/ext/edu/internet2/middleware/grouperClientExt/org/apache/commons/httpclient/methods/PostMethod.java,v 1.1 2008-11-30 10:57:19 mchyzer Exp $
18   * $Revision: 1.1 $
19   * $Date: 2008-11-30 10:57:19 $
20   *
21   * ====================================================================
22   *
23   *  Licensed to the Apache Software Foundation (ASF) under one or more
24   *  contributor license agreements.  See the NOTICE file distributed with
25   *  this work for additional information regarding copyright ownership.
26   *  The ASF licenses this file to You under the Apache License, Version 2.0
27   *  (the "License"); you may not use this file except in compliance with
28   *  the License.  You may obtain a copy of the License at
29   *
30   *      http://www.apache.org/licenses/LICENSE-2.0
31   *
32   *  Unless required by applicable law or agreed to in writing, software
33   *  distributed under the License is distributed on an "AS IS" BASIS,
34   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35   *  See the License for the specific language governing permissions and
36   *  limitations under the License.
37   * ====================================================================
38   *
39   * This software consists of voluntary contributions made by many
40   * individuals on behalf of the Apache Software Foundation.  For more
41   * information on the Apache Software Foundation, please see
42   * <http://www.apache.org/>.
43   *
44   */
45  
46  package edu.internet2.middleware.grouperClientExt.org.apache.commons.httpclient.methods;
47  
48  import java.util.Iterator;
49  import java.util.Vector;
50  
51  import edu.internet2.middleware.grouperClientExt.org.apache.commons.httpclient.NameValuePair;
52  import edu.internet2.middleware.grouperClientExt.org.apache.commons.httpclient.util.EncodingUtil;
53  import edu.internet2.middleware.grouperClientExt.org.apache.commons.logging.Log;
54  import edu.internet2.middleware.grouperClientExt.org.apache.commons.logging.LogFactory;
55  
56  /**
57   * Implements the HTTP POST method.
58   * <p>
59   * The HTTP POST method is defined in section 9.5 of 
60   * <a href="http://www.ietf.org/rfc/rfc2616.txt">RFC2616</a>:
61   * <blockquote>
62   * The POST method is used to request that the origin server accept the entity
63   * enclosed in the request as a new subordinate of the resource identified by
64   * the Request-URI in the Request-Line. POST is designed to allow a uniform
65   * method to cover the following functions:
66   * <ul>
67   *   <li>Annotation of existing resources</li>
68   *   <li>Posting a message to a bulletin board, newsgroup, mailing list, or 
69   *     similar group of articles</li>
70   *   <li>Providing a block of data, such as the result of submitting a form,
71   *     to a data-handling process</li>
72   *   <li>Extending a database through an append operation</li>
73   * </ul>
74   * </blockquote>
75   * </p>
76   *
77   * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
78   * @author <a href="mailto:dsale@us.britannica.com">Doug Sale</a>
79   * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
80   * @author Ortwin Gl???ck
81   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
82   * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
83   *
84   * @version $Revision: 1.1 $
85   * @since 1.0
86   */
87  public class PostMethod extends EntityEnclosingMethod {
88      // -------------------------------------------------------------- Constants
89  
90      /** Log object for this class. */
91      private static final Log LOG = LogFactory.getLog(PostMethod.class);
92  
93      /** The Content-Type for www-form-urlencoded. */
94      public static final String FORM_URL_ENCODED_CONTENT_TYPE = 
95          "application/x-www-form-urlencoded";
96  
97      /** 
98       * The buffered request body consisting of <code>NameValuePair</code>s. 
99       */
100     private Vector params = new Vector();
101 
102     // ----------------------------------------------------------- Constructors
103 
104     /**
105      * No-arg constructor.
106      *
107      * @since 1.0
108      */
109     public PostMethod() {
110         super();
111     }
112 
113     /**
114      * Constructor specifying a URI.
115      *
116      * @param uri either an absolute or relative URI
117      *
118      * @since 1.0
119      */
120     public PostMethod(String uri) {
121         super(uri);
122     }
123 
124     // ----------------------------------------------------- Instance Methods
125 
126     /**
127      * Returns <tt>"POST"</tt>.
128      *
129      * @return <tt>"POST"</tt>
130      *
131      * @since 2.0
132      */
133     public String getName() {
134         return "POST";
135     }
136 
137 
138     /**
139      * Returns <tt>true</tt> if there is a request body to be sent.
140      * 
141      * <P>This method must be overwritten by sub-classes that implement
142      * alternative request content input methods
143      * </p>
144      * 
145      * @return boolean
146      * 
147      * @since 2.0beta1
148      */
149     protected boolean hasRequestContent() {
150         LOG.trace("enter PostMethod.hasRequestContent()");
151         if (!this.params.isEmpty()) {
152             return true;
153         } else {
154             return super.hasRequestContent();
155         }
156     }
157 
158     /**
159      * Clears request body.
160      * 
161      * <p>This method must be overwritten by sub-classes that implement
162      * alternative request content input methods</p>
163      * 
164      * @since 2.0beta1
165      */
166     protected void clearRequestBody() {
167         LOG.trace("enter PostMethod.clearRequestBody()");
168         this.params.clear();
169         super.clearRequestBody();
170     }
171 
172     /**
173      * Generates a request entity from the post parameters, if present.  Calls
174      * {@link EntityEnclosingMethod#generateRequestBody()} if parameters have not been set.
175      * 
176      * @since 3.0
177      */
178     protected RequestEntity generateRequestEntity() {
179         if (!this.params.isEmpty()) {
180             // Use a ByteArrayRequestEntity instead of a StringRequestEntity.
181             // This is to avoid potential encoding issues.  Form url encoded strings
182             // are ASCII by definition but the content type may not be.  Treating the content
183             // as bytes allows us to keep the current charset without worrying about how
184             // this charset will effect the encoding of the form url encoded string.
185             String content = EncodingUtil.formUrlEncode(getParameters(), getRequestCharSet());
186             ByteArrayRequestEntityperClientExt/org/apache/commons/httpclient/methods/ByteArrayRequestEntity.html#ByteArrayRequestEntity">ByteArrayRequestEntity entity = new ByteArrayRequestEntity(
187                 EncodingUtil.getAsciiBytes(content),
188                 FORM_URL_ENCODED_CONTENT_TYPE
189             );
190             return entity;
191         } else {
192             return super.generateRequestEntity();
193         }
194     }
195     
196     /**
197      * Sets the value of parameter with parameterName to parameterValue. This method
198      * does not preserve the initial insertion order.
199      *
200      * @param parameterName name of the parameter
201      * @param parameterValue value of the parameter
202      *
203      * @since 2.0
204      */
205     public void setParameter(String parameterName, String parameterValue) {
206         LOG.trace("enter PostMethod.setParameter(String, String)");
207 
208         removeParameter(parameterName);
209         addParameter(parameterName, parameterValue);
210     }
211 
212     /**
213      * Gets the parameter of the specified name. If there exists more than one
214      * parameter with the name paramName, then only the first one is returned.
215      *
216      * @param paramName name of the parameter
217      *
218      * @return If a parameter exists with the name argument, the coresponding
219      *         NameValuePair is returned.  Otherwise null.
220      *
221      * @since 2.0
222      * 
223      */
224     public NameValuePair getParameter(String paramName) {
225         LOG.trace("enter PostMethod.getParameter(String)");
226 
227         if (paramName == null) {
228             return null;
229         }
230 
231         Iterator iter = this.params.iterator();
232 
233         while (iter.hasNext()) {
234             NameValuePair./../../../../../edu/internet2/middleware/grouperClientExt/org/apache/commons/httpclient/NameValuePair.html#NameValuePair">NameValuePair parameter = (NameValuePair) iter.next();
235 
236             if (paramName.equals(parameter.getName())) {
237                 return parameter;
238             }
239         }
240         return null;
241     }
242 
243     /**
244      * Gets the parameters currently added to the PostMethod. If there are no
245      * parameters, a valid array is returned with zero elements. The returned
246      * array object contains an array of pointers to  the internal data
247      * members.
248      *
249      * @return An array of the current parameters
250      *
251      * @since 2.0
252      * 
253      */
254     public NameValuePair[] getParameters() {
255         LOG.trace("enter PostMethod.getParameters()");
256 
257         int numPairs = this.params.size();
258         Object[] objectArr = this.params.toArray();
259         NameValuePairgrouperClientExt/org/apache/commons/httpclient/NameValuePair.html#NameValuePair">NameValuePair[] nvPairArr = new NameValuePair[numPairs];
260 
261         for (int i = 0; i < numPairs; i++) {
262             nvPairArr[i] = (NameValuePair) objectArr[i];
263         }
264 
265         return nvPairArr;
266     }
267 
268     /**
269      * Adds a new parameter to be used in the POST request body.
270      *
271      * @param paramName The parameter name to add.
272      * @param paramValue The parameter value to add.
273      *
274      * @throws IllegalArgumentException if either argument is null
275      *
276      * @since 1.0
277      */
278     public void addParameter(String paramName, String paramValue) 
279     throws IllegalArgumentException {
280         LOG.trace("enter PostMethod.addParameter(String, String)");
281 
282         if ((paramName == null) || (paramValue == null)) {
283             throw new IllegalArgumentException(
284                 "Arguments to addParameter(String, String) cannot be null");
285         }
286         super.clearRequestBody();
287         this.params.add(new NameValuePair(paramName, paramValue));
288     }
289 
290     /**
291      * Adds a new parameter to be used in the POST request body.
292      *
293      * @param param The parameter to add.
294      *
295      * @throws IllegalArgumentException if the argument is null or contains
296      *         null values
297      *
298      * @since 2.0
299      */
300     public void addParameter(NameValuePair param) 
301     throws IllegalArgumentException {
302         LOG.trace("enter PostMethod.addParameter(NameValuePair)");
303 
304         if (param == null) {
305             throw new IllegalArgumentException("NameValuePair may not be null");
306         }
307         addParameter(param.getName(), param.getValue());
308     }
309 
310     /**
311      * Adds an array of parameters to be used in the POST request body. Logs a
312      * warning if the parameters argument is null.
313      *
314      * @param parameters The array of parameters to add.
315      *
316      * @since 2.0
317      */
318     public void addParameters(NameValuePair[] parameters) {
319         LOG.trace("enter PostMethod.addParameters(NameValuePair[])");
320 
321         if (parameters == null) {
322             LOG.warn("Attempt to addParameters(null) ignored");
323         } else {
324             super.clearRequestBody();
325             for (int i = 0; i < parameters.length; i++) {
326                 this.params.add(parameters[i]);
327             }
328         }
329     }
330 
331     /**
332      * Removes all parameters with the given paramName. If there is more than
333      * one parameter with the given paramName, all of them are removed.  If
334      * there is just one, it is removed.  If there are none, then the request
335      * is ignored.
336      *
337      * @param paramName The parameter name to remove.
338      *
339      * @return true if at least one parameter was removed
340      *
341      * @throws IllegalArgumentException When the parameter name passed is null
342      *
343      * @since 2.0
344      */
345     public boolean removeParameter(String paramName) 
346     throws IllegalArgumentException {
347         LOG.trace("enter PostMethod.removeParameter(String)");
348 
349         if (paramName == null) {
350             throw new IllegalArgumentException(
351                 "Argument passed to removeParameter(String) cannot be null");
352         }
353         boolean removed = false;
354         Iterator iter = this.params.iterator();
355 
356         while (iter.hasNext()) {
357             NameValuePair/../../../../../../../edu/internet2/middleware/grouperClientExt/org/apache/commons/httpclient/NameValuePair.html#NameValuePair">NameValuePair pair = (NameValuePair) iter.next();
358 
359             if (paramName.equals(pair.getName())) {
360                 iter.remove();
361                 removed = true;
362             }
363         }
364         return removed;
365     }
366 
367     /**
368      * Removes all parameter with the given paramName and paramValue. If there
369      * is more than one parameter with the given paramName, only one is
370      * removed.  If there are none, then the request is ignored.
371      *
372      * @param paramName The parameter name to remove.
373      * @param paramValue The parameter value to remove.
374      *
375      * @return true if a parameter was removed.
376      *
377      * @throws IllegalArgumentException when param name or value are null
378      *
379      * @since 2.0
380      */
381     public boolean removeParameter(String paramName, String paramValue) 
382     throws IllegalArgumentException {
383         LOG.trace("enter PostMethod.removeParameter(String, String)");
384 
385         if (paramName == null) {
386             throw new IllegalArgumentException("Parameter name may not be null");
387         }
388         if (paramValue == null) {
389             throw new IllegalArgumentException("Parameter value may not be null");
390         }
391 
392         Iterator iter = this.params.iterator();
393 
394         while (iter.hasNext()) {
395             NameValuePair/../../../../../../../edu/internet2/middleware/grouperClientExt/org/apache/commons/httpclient/NameValuePair.html#NameValuePair">NameValuePair pair = (NameValuePair) iter.next();
396 
397             if (paramName.equals(pair.getName())
398                 && paramValue.equals(pair.getValue())) {
399                 iter.remove();
400                 return true;
401             }
402         }
403 
404         return false;
405     }
406 
407     /**
408      * Sets an array of parameters to be used in the POST request body
409      *
410      * @param parametersBody The array of parameters to add.
411      *
412      * @throws IllegalArgumentException when param parameters are null
413      * 
414      * @since 2.0beta1
415      */
416     public void setRequestBody(NameValuePair[] parametersBody)
417     throws IllegalArgumentException {
418         LOG.trace("enter PostMethod.setRequestBody(NameValuePair[])");
419 
420         if (parametersBody == null) {
421             throw new IllegalArgumentException("Array of parameters may not be null");
422         }
423         clearRequestBody();
424         addParameters(parametersBody);
425     }
426 }