View Javadoc

1   /*
2      Licensed under the Apache License, Version 2.0 (the "License");
3      you may not use this file except in compliance with the License.
4      You may obtain a copy of the License at
5   
6        http://www.apache.org/licenses/LICENSE-2.0
7   
8      Unless required by applicable law or agreed to in writing, software
9      distributed under the License is distributed on an "AS IS" BASIS,
10     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11     See the License for the specific language governing permissions and
12     limitations under the License.
13  */
14  package uk.nhs.interoperability.util;
15  
16  import java.io.IOException;
17  import java.io.InputStream;
18  
19  import javax.servlet.http.HttpServletRequest;
20  
21  /**
22   * The Class ServletUtils.
23   *
24   * @author Michael Odling-Smee
25   * @author Nicholas Jones
26   * @since 0.1
27   */
28  public class ServletUtils {
29  	
30  	//TODO make this more efficient (don't read one byte at a time)
31  	/**
32  	 * Read request content.
33  	 *
34  	 * @param req the req
35  	 * @return the byte[]
36  	 * @throws IOException Signals that an I/O exception has occurred.
37  	 */
38  	public static final byte[] readRequestContent(HttpServletRequest req) throws IOException {
39  			if (req != null) {
40  				Logger.debug("Reading servlet request; content length: " + req.getContentLength());
41  				InputStream in = req.getInputStream();		
42  				int bytesRead = 0;		
43  				int bytesToRead= req.getContentLength();
44  				byte[] payload = null;
45  				if (bytesToRead > 0) {
46  					payload = new byte[bytesToRead];
47  					while (bytesRead < bytesToRead) {
48  					  int result = in.read(payload, bytesRead, bytesToRead - bytesRead);
49  					  if (result == -1) {
50  						  break;
51  					  }
52  					  bytesRead += result;
53  					}
54  				}
55  				return payload;
56  			}
57  			return null;
58  	}
59  
60  }