001    // Copyright 2004, 2005 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry.test.mock;
016    
017    import java.io.FileInputStream;
018    import java.io.IOException;
019    import java.io.InputStream;
020    import java.io.OutputStream;
021    
022    import javax.servlet.RequestDispatcher;
023    import javax.servlet.ServletException;
024    import javax.servlet.ServletRequest;
025    import javax.servlet.ServletResponse;
026    
027    /**
028     * Used to enable mock testing of internal request forwarding.
029     *
030     * @author Howard Lewis Ship
031     * @since 4.0
032     */
033    public class MockRequestDispatcher implements RequestDispatcher
034    {       
035            private String _resourcePath;
036            
037        public MockRequestDispatcher(String resourcePath)
038        {
039            _resourcePath = resourcePath;
040        }
041    
042        public void forward(ServletRequest request, ServletResponse response)
043            throws ServletException, IOException
044        {
045            if (_resourcePath.endsWith("/FAIL_SERVLET"))
046                    throw new ServletException("Test-directed ServletException from RequestDispatcher forward().");
047            
048            // For testing purposes, assume we only forward to static HTML files.
049            
050            
051            InputStream in = new FileInputStream(_resourcePath);
052    
053                    response.setContentType("test/html");
054            
055            OutputStream out =      response.getOutputStream();
056    
057            
058            byte[] buffer = new byte[1000];
059            
060            while (true)
061            {
062                    int length = in.read(buffer);
063                    
064                    if (length < 0)
065                            break;
066                            
067                    out.write(buffer, 0, length);
068            }
069            
070            in.close();
071            out.close();
072        }
073    
074        public void include(ServletRequest request, ServletResponse response)
075            throws ServletException, IOException
076        {
077            throw new ServletException("MockRequestDispatcher.include() not supported.");
078        }
079    
080    }