Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 87 total  RSS 

Copy a file from one web server to another

This Ruby code is designed to copy a file from one web server to another. There's nothing special about the code however it can be quite helpful when 2 web servers can easily transfer files between each other using this approach.

   1  
   2  #!/usr/bin/ruby
   3  #file: getwebfile.rb
   4  
   5  require 'rio'
   6  require 'tempfile'
   7  
   8  class GetWebFile
   9  
  10    def initialize()
  11    end
  12  
  13    def get_file(url)
  14      filedir = '../temp/'
  15      filename = url[/\w+\.\w+$/]
  16      rio(url) > rio(filedir + filename)
  17      filedir + filename
  18    end  
  19  
  20    # use with cgi; retrieve the projectx xml interface parameter 'file_url'
  21    def call_get_web_file(params)
  22      h = Hash.new
  23      doc = Document.new(params)
  24      file_url = get_param(doc,'file_url')
  25      get_file(file_url)
  26    end
  27  
  28    def get_param(doc, var)
  29      node = doc.root.elements["param[@var='#{var}']"]
  30      node.text.to_s
  31    end 
  32  end
  33  
  34  if __FILE__ == $0
  35      g = GetWebFile.new()
  36      g.get_file('http://192.168.1.107/audio/prompt01.wav')
  37  end


Output (ls ../temp -ltr):
   1  -rw-r--r-- 1 root   root   161804 Oct  6 17:45 prompt01.wav


Here's a sample ProjectX interface used for querying the ProjectX web service
   1  
   2  <project name="convert_audio">
   3    <methods>
   4      <method name="get_web_file">
   5        <params>
   6          <param var='file_url'>http://192.168.1.107/audio/prompt01.wav</param>
   7        </params>
   8      </method>
   9    </method>
  10  </project>


Background:
I intended to convert a wav file to ogg but rather than install the necessary vorbis tools for each machine I realised it would be easier just to call a web service. Each web server will be set up with a 'get_web_file' kind of service, the 1st web server will request the 2nd web server to fetch the wav file. That will then convert it to ogg and request the 1st web server to fetch the ogg file from it's location.

Resources:
- Rio [rubyforge.org]
- Using Rio from Ruby to easily save a Web page to file [dzone.com]

Embed an OGG video on a web page

This code was copied from an HTML page from Superman: The Arctic Giant [xiph.org]

   1  
   2  <video id="testvideo" style="display:none"></video>
   3  
   4  
   5  <script language="JavaScript">
   6  var vlcActiveX = false;
   7  var vlcPlugin = false;
   8  var videoElement = false;
   9  var oggPlugin = false;
  10  var javaEnabled = false;
  11  </script>
  12  <script language="vbScript">
  13  on error resume next
  14  vlcActiveX = (IsObject(CreateObject("VideoLAN.VLCPlugin.2")))
  15  </script>
  16  
  17  
  18  <script language="JavaScript">
  19  
  20  function embedVideoElement(location, width, height) {
  21    document.write("<video style=\"width:" + width + ";height:" + height + ";\" src='" + location + "' id='video_element'></video><br>");
  22    document.write("<input type='button' value='play' onClick='document.getElementById(\"video_element\").play()'>");
  23    document.write("<input type='button' value='stop' onClick='document.getElementById(\"video_element\").pause(); document.getElementById(\"video_element\").start = 0;'>");
  24  }
  25  
  26  function embedOggPlugin(location, width, height) {
  27    document.write("<object type='application/ogg' width='"+width+"' height='"+height+"' data='" + location + "'></object>");
  28  }
  29  
  30  function embedVlcPlugin(location, width, height) {
  31    document.write("<object type='application/x-vlc-plugin' id='vlc_element' width='"+width+"' height='"+height+"' data='" + location + "'></object><br>");
  32    document.write("<input type='button' value='play' onClick='document.getElementById(\"vlc_element\").play()'>");
  33    document.write("<input type='button' value='stop' onClick='document.getElementById(\"vlc_element\").stop()'>");
  34  }
  35  
  36  
  37  function embedVlcActiveX(location,width,height) {
  38    document.write("<object classid='clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921' codebase='http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab#Version=0,8,6,0' width='"+width+"' height='"+height+"' id='vlc_element'>");
  39    document.write("<param name='MRL' value='" + location +"'>");
  40    document.write("</object><br>");
  41    document.write("<input type='button' value='play' onClick='document.getElementById(\"vlc_element\").playlist.play()'>");
  42    document.write("<input type='button' value='stop' onClick='document.getElementById(\"vlc_element\").playlist.stop()'>");
  43  }
  44  
  45  function embedCortado(location,width,height) {
  46    document.write("<applet code='com.fluendo.player.Cortado.class' archive='cortado.jar' width='"+width+"' height='"+height+"'>");
  47    document.write("<param name='url' value='" + location + "'>");
  48    document.write("</applet>");
  49  }
  50  
  51  
  52  
  53  if(document.getElementsByTagName("video").length > 0) {
  54    var myvideo = document.getElementById("testvideo");
  55    if(myvideo.play) {
  56      videoElement = true;
  57    }
  58  }
  59  
  60  var searchedMimeTypes = false;
  61  var foundJavaMimeType = false;
  62  
  63  if(navigator.mimeTypes && navigator.mimeTypes.length > 0) {
  64  
  65    searchedMimeTypes = true;
  66  
  67    for (var i = 0; i < navigator.mimeTypes.length; i++) {
  68      if(navigator.mimeTypes[i].type.indexOf("application/ogg") > -1) {
  69        oggPlugin = true;
  70      }
  71      if(navigator.mimeTypes[i].type.indexOf("application/x-vlc-plugin") > -1) {
  72        vlcPlugin = true;
  73      }	
  74      if(navigator.mimeTypes[i].type.indexOf("application/x-java-applet") > -1) {
  75        foundJavaMimeType = true;
  76      }
  77    }
  78  
  79  }
  80  
  81  
  82  var nativePlayback = vlcActiveX || vlcPlugin || videoElement || oggPlugin;
  83   
  84  if(searchedMimeTypes) {
  85    javaEnabled = navigator.javaEnabled() && foundJavaMimeType;
  86  } else {
  87    javaEnabled = navigator.javaEnabled();
  88  }
  89  
  90  
  91  var file = "arctic_giant.ogg";
  92  var width = 512;
  93  var height = 384;
  94  
  95  if(videoElement) {
  96    embedVideoElement(file,width,height);
  97  } else if(vlcPlugin) {
  98    embedVlcPlugin(file,width,height);
  99  } else if(vlcActiveX) {
 100    embedVlcActiveX(file,width,height);
 101  } else if(oggPlugin) {
 102    embedOggPlugin(file,width,height);
 103  } else if(javaEnabled) {
 104    embedCortado(file,width,height);
 105  }
 106  
 107  </script>
 108  


See also another example of embedded OGG video with information about Saint Lucia [wikipedia.org]

Inspect a website like a string in Ruby

Put the following function into your ~/.bash_login (or alternatives).

   1  
   2  unset -f inspect_url
   3  
   4  function inspect_url() { 
   5     /usr/bin/curl -L -s --max-time 10 "${@}" | ruby -n -e 'p $_.to_s'
   6     return 0
   7  }
   8  
   9  inspect_url http://www.ruby-forum.com

GET stream from the web using python

GETs files from a remote webserver. I'm using it for streaming
   1  
   2  def get(host,port,url):
   3      h = httplib.HTTP(host, port)
   4      h.putrequest('GET', url)
   5      h.putheader('Host', host)
   6      h.putheader('User-agent', 'python-httplib')
   7      h.endheaders()
   8  
   9      (returncode, returnmsg, headers) = h.getreply()
  10      if returncode != 200:
  11          print returncode, returnmsg
  12          sys.exit()
  13  
  14      f = h.getfile()
  15      return f.read()

Compile & install Nginx web server

Requirement on Mac OS X: Xcode

   1  
   2  # See:
   3  # - http://en.wikipedia.org/wiki/Nginx
   4  # - http://wiki.codemongers.com/NginxGettingStarted
   5  # - http://wiki.codemongers.com/NginxInstallOptions
   6  # - http://wiki.codemongers.com/NginxCommandLine
   7  # - http://wiki.codemongers.com/NginxConfiguration
   8  
   9  export PATH="/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
  10  
  11  mkdir -p ~/Desktop/Nginx
  12  cd ~/Desktop/Nginx
  13  
  14  curl -L -O http://sysoev.ru/nginx/nginx-0.7.2.tar.gz
  15  tar -xzf nginx-0.7.2.tar.gz
  16  
  17  curl -L -O http://downloads.sourceforge.net/pcre/pcre-7.7.tar.gz
  18  tar -xzf pcre-7.7.tar.gz
  19  
  20  cd ~/Desktop/Nginx/nginx-0.7.2
  21  ./configure --help
  22  ./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/sbin --with-debug --with-http_ssl_module --with-pcre=../pcre-7.7
  23  make
  24  sudo make install
  25  
  26  
  27  which nginx
  28  otool -L /usr/local/sbin/nginx
  29  open /usr/local/nginx
  30  open -e /usr/local/nginx/conf/nginx.conf
  31  
  32  nginx -v
  33  nginx -V
  34  sudo nginx   # start server
  35  sudo nginx -t
  36  
  37  open http://localhost:80
  38  open http://localhost:80/50x.html
  39  
  40  sudo nano /usr/local/nginx/conf/nginx.conf   # editing ... server {  listen  8080; ... 
  41  
  42  # reload configuration
  43  sudo kill -HUP `cat /usr/local/nginx/logs/nginx.pid`  
  44  
  45  # stop server
  46  sudo kill -15 $(ps -auxxx | egrep "[n]ginx.*master" | awk '{ print $2 }') 2>/dev/null

Basic WEBrick setup for local web server

Put the following functions and aliases into your ~/.bash_login (or alternatives).

   1  
   2  
   3  unset -f webrick_local
   4  
   5  function webrick_local() { 
   6  
   7     declare root_dir="${HOME}/Desktop/www"
   8  
   9     /bin/mkdir -p "${root_dir}/WEBrickLog"
  10     /bin/chmod 0754 "${root_dir}" "${root_dir}/WEBrickLog"
  11  
  12     /usr/bin/touch "${root_dir}/WEBrickLog/webrick.pid" "${root_dir}/WEBrickLog/webrick_ruby.pid"
  13     /bin/chmod 0644 "${root_dir}/WEBrickLog/webrick.pid" "${root_dir}/WEBrickLog/webrick_ruby.pid"
  14  
  15  #   /usr/bin/touch "${root_dir}/index.html"
  16  #   /bin/chmod 0754 "${root_dir}/index.html"
  17  
  18  
  19  /usr/local/bin/ruby <<-HEREDOC
  20  
  21     require 'webrick'
  22     require 'webrick/accesslog'
  23     include WEBrick
  24  
  25     require 'thread'
  26     require 'pp'
  27  
  28     root_dir = "${root_dir}"
  29     http_dir = File.expand_path(root_dir)
  30  
  31     File.open(http_dir + "/WEBrickLog/webrick_ruby.pid", "w") do |f|
  32        f.puts(Process.pid)
  33     end
  34  
  35     # cf. http://microjet.ath.cx/webrickguide/html/Logging.html
  36     webrick_log_file = File.expand_path(http_dir + "/WEBrickLog/webrick.log")
  37     #webrick_log_file = '/dev/null'  # disable logging
  38     webrick_logger = WEBrick::Log.new(webrick_log_file, WEBrick::Log::DEBUG)
  39  
  40     access_log_stream = webrick_logger
  41     access_log = [[ access_log_stream, WEBrick::AccessLog::COMBINED_LOG_FORMAT ]]
  42  
  43     system_mime_table = WEBrick::HTTPUtils::load_mime_types('/private/etc/httpd/mime.types.default')
  44     system_mime_table.store('rhtml', 'text/html')   # add a mime type for .rhtml files
  45     system_mime_table.store('php', 'text/html')
  46     system_mime_table.store('rb', 'text/plain')
  47     system_mime_table.store('pid', 'text/plain')
  48     #pp system_mime_table.sort_by { |k,v| k }
  49  
  50     server = WEBrick::HTTPServer.new(
  51       :BindAddress     =>    "localhost",
  52       :Port            =>    9090,
  53       :DocumentRoot    =>    http_dir,
  54       :FancyIndexing   =>    true,
  55       :MimeTypes       =>    system_mime_table,
  56       :Logger          =>    webrick_logger,
  57       :AccessLog       =>    access_log
  58     )
  59  
  60     server.config.store(:DirectoryIndex, server.config[:DirectoryIndex] << "default.htm")
  61     #pp server.config
  62  
  63     # cf. http://snippets.dzone.com/posts/show/5208
  64     class TimeServlet < HTTPServlet::AbstractServlet
  65  
  66        def do_GET(req, res)
  67           res['Content-Type'] = 'text/html'
  68           res.status = 200
  69           res.body = "<html>Time: #{Time.now.to_s}</html>" + "\n"
  70        end
  71  
  72        # cf. http://www.hiveminds.co.uk/node/244, published under the
  73        # GNU Free Documentation License, http://www.gnu.org/copyleft/fdl.html
  74  
  75        @@instance = nil
  76        @@instance_creation_mutex = Mutex.new
  77  
  78        def self.get_instance(config, *options)
  79           #pp @@instance
  80           @@instance_creation_mutex.synchronize { 
  81              @@instance = @@instance || self.new(config, *options) }
  82        end
  83  
  84     end
  85  
  86  
  87     # cf. http://ttripp.blogspot.com/2007/01/fun-with-http.html
  88     class PostDumper < WEBrick::HTTPServlet::AbstractServlet
  89    
  90        # Reload file for each request, instantly
  91        # updating the server with code changes 
  92        # without needing a restart.
  93  
  94  =begin
  95        def PostDumper.get_instance( config, *options )
  96           load __FILE__
  97           PostDumper.new config, *options
  98        end
  99  =end
 100  
 101        # cf. http://www.hiveminds.co.uk/node/244, published under the
 102        # GNU Free Documentation License, http://www.gnu.org/copyleft/fdl.html
 103  
 104        @@instance = nil
 105        @@instance_creation_mutex = Mutex.new
 106  
 107        def self.get_instance(config, *options)
 108           #pp @@instance
 109           @@instance_creation_mutex.synchronize { 
 110              @@instance = @@instance || self.new(config, *options) }
 111        end
 112  
 113        def do_GET( request, response )
 114           response.status = 200
 115           response['Content-Type'] = "text/plain"
 116           response.body = dump_request( request )
 117        end
 118    
 119        def do_POST( request, response )
 120           response.status = 200
 121           response['Content-Type'] = "text/plain"
 122           response.body = dump_request( request )
 123           response.body << request.body
 124        end
 125    
 126        def dump_request( request )
 127           request.request_line << "\r\n" <<
 128           request.raw_header.join( "" ) << "\r\n"
 129        end
 130     end
 131  
 132     server.mount("/dump", PostDumper)
 133     server.mount("/time", TimeServlet, {:FancyIndexing=>true})
 134  
 135     # handle signals
 136     %w(INT).each do |signal|
 137        trap(signal) { server.shutdown }
 138     end
 139  
 140     server.start
 141  
 142  HEREDOC
 143  
 144  return 0
 145  
 146  }
 147  
 148  export -f webrick_local
 149  
 150  # start WEBrick alias
 151  alias webrick='swr'
 152  
 153  # start WEBrick
 154  unset -f swr
 155  function swr() {   
 156    declare webrick_pid_file="${HOME}/Desktop/www/WEBrickLog/webrick.pid"
 157    if [[ -e "${webrick_pid_file}" ]]; then echo "WEBrick already started!"; return 1; fi
 158    /bin/bash -c "webrick_local" &
 159    declare WEBRICKPID=$!
 160    mkdir -p "${HOME}/Desktop/www/WEBrickLog"
 161    echo $WEBRICKPID > "${HOME}/Desktop/www/WEBrickLog/webrick.pid"
 162    return 0
 163  }
 164  export -f swr
 165  
 166  # quit WEBrick
 167  unset -f qwr
 168  function qwr() { 
 169     declare webrick_pid_file="${HOME}/Desktop/www/WEBrickLog/webrick.pid"
 170     declare webrick_ruby_pid_file="${HOME}/Desktop/www/WEBrickLog/webrick_ruby.pid"
 171     if [[ ! -e "${webrick_pid_file}" ]]; then echo "no such file: ${webrick_pid_file}"; return 1; fi
 172     declare PIDW=$(cat "${webrick_pid_file}" 2>/dev/null)
 173     declare PIDR=$(cat "${webrick_ruby_pid_file}" 2>/dev/null)
 174     kill -INT $PIDW 2>/dev/null || echo "no such PIDW: ${PIDW}"
 175     kill -INT $PIDR 2>/dev/null || echo "no such PIDR: ${PIDR}"
 176     rm -f "${webrick_pid_file}" "${webrick_ruby_pid_file}"
 177     return 0
 178  }
 179  export -f qwr
 180  
 181  # quit WEBrick; cf. Job Control Commands, http://tldp.org/LDP/abs/html/x8816.html
 182  ###alias qwr='echo "quit WEBrick with ctrl-c ..."; fg %webrick 2>/dev/null'
 183  
 184  alias openwww='/usr/bin/open http://localhost:9090'
 185  alias wrlog='/usr/bin/open http://localhost:9090/WEBrickLog/webrick.log'
 186  
 187  
 188  #----------------------------------------
 189  
 190  
 191  source ~/.bash_login
 192  
 193  webrick
 194  
 195  openwww
 196  wrlog
 197  open http://localhost:9090 
 198  open http://localhost:9090/WEBrickLog
 199  open http://localhost:9090/WEBrickLog/webrick.log
 200  
 201  open http://localhost:9090/time
 202  open http://localhost:9090/dump
 203  
 204  wrlog
 205  qwr


Further information:

- WEBrick
- WEBrick RDoc
- What is WEBrick?
- Guide to using WEBrick for Rails development
- Dynamic WEBrick Servers in Ruby
- Gnome's Guide to WEBrick
- Running Servlets with WEBrick
- rsphandler
- URL rewriting with WEBrick

Pattern Matching based WSGI-enabled URL routing tool.

Actual version on http://pypi.python.org/pypi/decoroute

   1  
   2  easy_install decoroute


Example:

   1  
   2  import decoroute
   3      
   4  app = decoroute.App()
   5      
   6  def render_response(status = '200 OK', **kw):
   7      # try your favorite templating engine here
   8      return status, [('Content-Type', 'text/plain')], [str(kw)]
   9  
  10  def redirect_to(env, endpoint, **kw):
  11      return '302 FOUND', [('Content-Type', 'text/plain'), \
  12      ('Location', '%s://%s%s' % (env['wsgi.url_scheme'], env['HTTP_HOST'], \
  13      env['decoroute.app'].url_for(endpoint, **kw)))], ['']
  14      
  15  @app.expose('/node', id = '1')
  16  @app.expose('/node/<id:\d+>')
  17  def node(env, id):
  18      return render_response(id = id)
  19      
  20  @app.expose('/url_for')
  21  def url_for(env):
  22      return render_response( \
  23          url = env['decoroute.app'].url_for(node, id = 666))
  24      
  25  @app.expose('/302')
  26  def found(env):
  27      return redirect_to(env, not_found)
  28      
  29  @app.expose('/404')
  30  def not_found(env):
  31      raise decoroute.NotFound()
  32      
  33  @app.not_found()
  34  def not_found_handler(env):
  35      return render_response('404 NF', url = env['PATH_INFO'])
  36      
  37  from wsgiref.simple_server import make_server
  38      
  39  make_server('', 5555, app).serve_forever()


Complete source < 100 lines of code:

   1  
   2  #!/usr/bin/env python
   3  # vim:ts=4:sw=4:et
   4  # -*- coding: utf-8 -*-
   5  # $Id: decoroute.py,v 6eb37aeee5cd 2008/06/09 07:38:26 vsevolod $
   6  #
   7  # Pattern Matching based WSGI-enabled URL routing tool.
   8  # Actual version on http://pypi.python.org/pypi/decoroute
   9  # (C) 2008 by Vsevolod S. Balashov <vsevolod@balashov.name>
  10  # under terms of GNU LGPL v2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt
  11  
  12  __author__ = "Vsevolod Balashov"
  13  __email__ = "vsevolod at balashov dot name"
  14  
  15  import re
  16  from sets import ImmutableSet
  17  import wsgistraw
  18  
  19  __all__ = ['NotFound', 'App']
  20  
  21  class NotFound(Exception):
  22      pass
  23  
  24  _pattern_re = re.compile(r'''
  25      ([^<]+)                     # static rule data
  26      (?:<
  27          ([a-zA-Z][a-zA-Z0-9_]*) # variable name
  28          \:
  29          ([^>]+)                 # regexp constraint
  30      >)?
  31  ''', re.VERBOSE)
  32  
  33  def pattern2regexp(pattern, f, s = lambda x: re.escape(x)):
  34      def parser():
  35          for t in _pattern_re.findall(pattern):
  36              yield s(t[0])
  37              if t[1] != '':
  38                  yield f(t[1], t[2])
  39      return parser()
  40  
  41  make_url_for = lambda p: ''.join(pattern2regexp(p, lambda v, r: '%%(%s)s' % v, lambda s: s))
  42  make_variables = lambda p: filter(lambda x: x, pattern2regexp(p, lambda v, r: v, lambda s: None))
  43  make_pattern = lambda p: r''.join(pattern2regexp(p, lambda v, r: r'(?P<%s>%s)' % (v, r)))
  44  make_selector_fragment = lambda p: r''.join(pattern2regexp(p, lambda v, r: r'(?:%s)' % r))
  45  make_selector = lambda i: re.compile(r'(^%s$)' % r'$)|(^'.join(map(make_selector_fragment, i)))
  46  
  47  class UrlMap(object):
  48      def __init__(self):
  49          self._endpoints = {}
  50          self._patterns = {}
  51          self._pattern_selector = make_selector(self._patterns.iterkeys())
  52      
  53      def add(self, pattern, endpoint, **kw):
  54          if self._patterns.has_key(pattern):
  55              raise Exception('duplicate pattern', pattern)
  56          self._endpoints[(endpoint, ImmutableSet(make_variables(pattern)))] = make_url_for(pattern)
  57          self._patterns[pattern] = (re.compile(make_pattern(pattern)), endpoint, kw)
  58          self._pattern_selector = make_selector(self._patterns.iterkeys())
  59      
  60      def route(self, url):
  61          try:
  62              p = self._patterns.values()[re.match(self._pattern_selector, url).lastindex - 1]
  63              d = re.match(p[0], url).groupdict().copy()
  64              d.update(p[2])
  65              return p[1], d
  66          except:
  67              raise NotFound('route not found', url)
  68      
  69      def url_for(self, endpoint, **kw):
  70          return self._endpoints[(endpoint, ImmutableSet(kw.keys()))] % kw
  71  
  72  class App(object):
  73      def __init__(self, key = 'decoroute.app'):
  74          self._key = key
  75          self._map = UrlMap()
  76          self._not_found = lambda e: ('404 NOT FOUND', [("Content-Type", "text/plain")], [''])
  77      
  78      @wsgistraw.app
  79      def __call__(self, env):
  80          try:
  81              env[self._key] = self
  82              endpoint, kw = self._map.route(env['PATH_INFO'])
  83              return endpoint(env, **kw)
  84          except NotFound:
  85              return self._not_found(env)
  86      
  87      def expose(self, pattern, **kw):
  88          def decorate(f):
  89              self._map.add(pattern, f, **kw)
  90              return f
  91          return decorate
  92      
  93      def not_found(self):
  94          def decorate(f):
  95              self._not_found = f
  96              return f
  97          return decorate
  98      
  99      def url_for(self, endpoint, **kw):
 100          return self._map.url_for(endpoint, **kw)

One-line web server in Ruby

   1  
   2  
   3  # From: http://www.ntecs.de/blog/articles/2008/02/09/the-worlds-smallest-webserver
   4  # Author: Michael Neumann
   5  # ... point your browser to http://localhost:3125/etc/motd
   6  
   7  ruby -rsocket -e 's=TCPServer.new(5**5);loop{_=s.accept;_<<"HTTP/1.0 200 OK\r\n\r\n#{File.read(_.gets.split[1])rescue nil}";_.close}'
   8  

Run TCPServer as a simple Web server

A TCPServer accepts incoming TCP connections. Here is a Web server that listens on a given port and returns the time.

   1  
   2  require 'socket'
   3  port = (ARGV[0] || 80).to_i
   4  server = TCPServer.new('localhost', port)
   5  while (session = server.accept)
   6    puts "Request: #{session.gets}"
   7    session.print "HTTP/1.1 200/OK\r\nContent-type: text/html\r\n\r\n"
   8    session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
   9    session.close
  10  end

This code was copied from Programming Ruby: The Pragmatic Programmer's Guide [rubycentral.com] while looking for information on Ruby CGI global variables.

Upload a file using Ruby

The following code was used to upload an image file to the web server. Source code origin: Ruby Language Stuff | mod_ruby File upload scripts [zytrax.com]

file: file_upload.cgi
   1  
   2  #!/usr/bin/ruby
   3  
   4  # ruby script fragment
   5  require 'cgi'
   6  require 'stringio'
   7  
   8  cgi = CGI.new()  # New CGI object
   9  puts "Content-Type: text/plain"
  10  puts
  11  print '<result>'
  12  
  13  # get uri of tx'd file (in tmp normally)
  14  tmpfile = cgi.params['myfile'].first.path
  15  
  16  # OR (functionally the same)
  17  tmpfile = cgi.params['myfile'][0].path
  18  
  19  # create a Tempfile reference
  20  fromfile = cgi.params['myfile'].first
  21  
  22  #displays the original file name as supplied in the form
  23  puts fromfile.original_filename
  24  
  25  # displays the content (mime) type e.g. text/html
  26  puts fromfile.content_type
  27  
  28  # create output file reference as original filename in our chosen directory
  29  tofile = '/var/www/yourdomain.com/htdocs/r/'+fromfile.original_filename
  30  
  31  # copy the file
  32  # note the untaint prevents a security error
  33  # cgi sets up an StringIO object if file < 10240
  34  # or a Tempfile object following works for both
  35  File.open(tofile.untaint, 'w') { |file| file << fromfile.read}
  36  # when the page finishes the Tempfile/StringIO!) thing is deleted automatically
  37  
  38  print '</result>'

file: file_upload.html
   1  
   2  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   3    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
   4  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
   5    <head>
   6      <title>File upload</title>
   7      <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
   8    </head>
   9    <body>
  10      <form name='fileupload' enctype="multipart/form-data" 
  11      action='/p/file_upload.cgi' method='post'>
  12      <input type='file' name='myfile' size="40" />
  13      <input type='submit' value"Send it"/>
  14      </form>
  15    </body>
  16  </html>
  17    
« Newer Snippets
Older Snippets »
Showing 1-10 of 87 total  RSS