#--
# Copyright (c) 2010-2012 Engine Yard, Inc.
# Copyright (c) 2007-2009 Sun Microsystems, Inc.
# This source code is available under the MIT license.
# See the file LICENSE.txt for details.
#++

begin
  require 'rack'
rescue LoadError
  require 'vendor/rack'
end unless defined?(::Rack::RELEASE)

# Servlet API friendly extensions to Rack
# Allows for forwarding the request to another servlet/JSP
# as well as server-side include of content generated by a servlet/JSP
module JRuby
  module Rack
    module RackExt
      module Request
        java_import org.jruby.rack.servlet.ServletRackIncludedResponse
        
        def forward_to(path, params={})
          servlet_request = env['java.servlet_request']
          params.each { |k,v| servlet_request[k.to_s] = v}
          servlet_response = env['java.servlet_response']
          servlet_request.getRequestDispatcher(path).forward(servlet_request, servlet_response)
        end

        # Returns the output of the server-side include as a string, honoring the character
        # encoding set on the response.
        def render(path, params={})
          servlet_request = env['java.servlet_request']
          params.each { |k,v| servlet_request[k.to_s] = v }
          servlet_response = ServletRackIncludedResponse.new(env['java.servlet_response'])
          servlet_request.getRequestDispatcher(path).include(servlet_request, servlet_response)
          servlet_response.getOutput
        end
      end

      ::Rack::Request.module_eval do
        include ::JRuby::Rack::RackExt::Request
      end
    end
  end
end

