View Javadoc

1   /*
2    * Copyright 2002,2004 The Apache Software Foundation.
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  package org.apache.commons.jelly.tags.http;
18  
19  import java.net.MalformedURLException;
20  
21  import org.apache.commons.httpclient.HttpMethod;
22  import org.apache.commons.httpclient.methods.PostMethod;
23  import org.apache.commons.httpclient.methods.PutMethod;
24  import org.apache.commons.jelly.JellyTagException;
25  import org.apache.commons.jelly.TagSupport;
26  import org.apache.commons.jelly.XMLOutput;
27  
28  /***
29   * A tag to set the body for posts and puts etc
30   *
31   * @author  dion
32   * @version $Id: BodyTag.java 155420 2005-02-26 13:06:03Z dirkv $
33   */
34  public class BodyTag extends TagSupport {
35  
36      /*** Creates a new instance of BodyTag */
37      public BodyTag() {
38      }
39  
40      /***
41       * Perform the tag functionality. In this case, get the parent http tag,
42       * and if it's a post or put, set the request body from the body of this
43       * tag.
44       *
45       * @param xmlOutput for writing output to
46       * @throws Exception when any error occurs
47       */
48      public void doTag(XMLOutput xmlOutput) throws JellyTagException {
49          HttpTagSupport httpTag = (HttpTagSupport) findAncestorWithClass(
50              HttpTagSupport.class);
51  
52          HttpMethod httpMethod = null;
53          try {
54              httpMethod = httpTag.getHttpMethod();
55          } catch (MalformedURLException e) {
56              throw new JellyTagException(e);
57          }
58  
59          String bodyText = getBodyText();
60          if (httpMethod instanceof PostMethod) {
61              PostMethod postMethod = (PostMethod) httpMethod;
62              postMethod.setRequestBody(bodyText);
63          } else if (httpMethod instanceof PutMethod) {
64              PutMethod putMethod = (PutMethod) httpMethod;
65              putMethod.setRequestBody(bodyText);
66          } else {
67              throw new IllegalStateException("Http method from parent was "
68                  + "not post or put");
69          }
70      }
71  
72  }