Sha256: 2c3b7276482dbb312856ece071a7ceab138d7de12398e6329d633955582a4d7f

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

class HTTPProviderException<Exception
  
end

# provides direct access to web-servlets
class HTTPProvider
  require 'webrick'
  include WEBrick
  
  attr_reader :thread
  
  @@mutex=Mutex.new

  def initialize(app,port=80)
    @@mutex.synchronize do
      @app=app
      @@webricks||={}
      if @@webricks[port]
        raise HTTPProviderException.new("Webrick on #{port} already exists!")
      end
      @s = HTTPServer.new(
       :Port => port,
       :DocumentRoot=>File.expand_path("../http/static",__FILE__),
       :BindAddress=>"127.0.0.1",
       :Logger=>WebrickLogger.new(@app)
      )
      @@webricks[port]=self
      @started=false
      
    end
  end
  
  def add(app,controller,controllerName=nil)
    controllerName||="/"+File.split(controller)[1].gsub(/\.rb/,"")
    puts "MOUNT #{controllerName}"
    
    @s.mount_proc(controllerName){|req, res|
      puts "REQUEST <#{req.path_info}>"
      load controller if $DEBUGGING
      listenerClass=getClass(controller.gsub(/.*\//,"").gsub(".rb","").camelCase)
      l=listenerClass.new(app)
      func=req.path_info[1..-1]
      l.params=req.query
      pp "REQ::::::",req
      args=req.post
      begin
        l.run(res,func,args)
      rescue HTTPController::UnknownAction=>e
        
        puts "TRY FIND FILE"
        # try to find a file
        path=func.to_s
        path.gsub!(/^(\.\.\/)*/,"")
        raise e unless l.render_static(res,path)
      end
    }
    
  end
  
  def run
    @thread=Thread.new {
      trap("INT"){ @s.shutdown }
      puts "Starting Webrick #{@s}"
      unless @started
        @started=true
        begin 
          @s.start
        rescue WEBrick::HTTPStatus::EOFError=>e
          pp e,e.backtrace
        rescue WEBrick::HTTPStatus::NotFound=>e
          pp e,e.backtrace
        end
      end 
    }
  end
  def stop
    @thread.kill
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
appswarm-0.0.1 lib/appswarm/http/http_provider.rb