View Javadoc

1   /*
2    * Copyright 1999-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  package org.apache.struts.flow.sugar;
17  
18  import org.mozilla.javascript.*;
19  
20  import java.io.*;
21  import java.util.*;
22  
23  /***
24   * Adds various functions to java.io.InputStream
25   * @targetClass java.io.InputStream
26   */
27  public class InputStreamExtensions {
28  
29  
30      /***
31       *  Gets the contents of the stream as a String.
32       *
33       *  @funcParams 
34       *  @funcReturn String
35       *  @example text = inStream.getText()
36       */
37      public static ExtensionFunction getText(final InputStream in) {
38          return new ExtensionFunction() {    
39              public Object execute(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) 
40                      throws IOException {
41                  
42                  BufferedReader reader = new BufferedReader(new InputStreamReader(in));
43                  StringBuffer answer = new StringBuffer();
44                  // reading the content of the file within a char buffer allow to keep the correct line endings
45                  char[] charBuffer = new char[4096];
46                  int nbCharRead = 0;
47                  while ((nbCharRead = reader.read(charBuffer)) != -1) {
48                      // appends buffer
49                      answer.append(charBuffer, 0, nbCharRead);
50                  }
51                  reader.close();
52                  return answer.toString();
53              }
54          };
55      }
56  }