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 10 total  RSS 

Redirect a URL with Ruby CGI

#!/usr/bin/ruby

require 'cgi'

cgi = CGI.new
print cgi.header({'Status' => '302 Moved', 'location' =>  'http://www.wired.com'})

or
url = 'http://www.wired.com/'
print cgi.header({'status'=>'REDIRECT', 'Location'=>url})


References:
RE: cgi redirect [nagaokaut.ac.jp]
Ruby/CGI - assari [mokehehe.com]
HTTP/1.1: Status Code Definitions [w3.org]

Instruct a shared whiteboard to save and refresh

The following code used with the ProjectX API informs the client web browser that the whiteboard will be refreshed in 5 seconds. It then archives the current whiteboard information, formats it, and sends a message to each web browser to refresh their view.

<project name="whiteboardqueue">
  <methods>
    <method name="create">
      <params>
        <param var="type">ecmascript</param>
        <param var="body">startRefresh(5)</param>
        <param var="sender">system</param>
      </params>
    </method>
    <method name="timer">
      <params>
        <param var="timer">5</param>
      </params>
    </method>
    <method name="archive_and_format">
      <params/>
    </method>
    <method name="create">
      <params>
        <param var="type">ecmascript</param>
        <param var="body">reloadDocument()</param>
        <param var="sender">system</param>
      </params>
    </method>
  </methods>
</project>


*update 1:14am*
The whiteboard demo [rorbuilder.info] allows the user to draw using the mouse within the web browser which renders SVG. Tested on Flock and Firefox.

*update 4:42pm 28 Mar 08*
You can also view the whiteboard message queue [rorbuilder.info].

*update 6:29pm Mar 08*
I've created a short url (http://rubyurl.com/vxHD) (to demonstrate the cleaning of the whiteboard) which redirects to this http://rorbuilder.info/api/projectx.cgi?xml_project=<project name="whiteboardqueue"><methods><method name="create"><params><param var="type">ecmascript</param><param var="body">startRefresh(5)</param><param var="sender">system</param></params></method><method name="timer"><params><param var="timer">5</param></params></method><method name="archive_and_format"><params/></method><method name="create"><params><param var="type">ecmascript</param><param var="body">reloadDocument()</param><param var="sender">system</param></params></method></methods></project>

I've

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
#!/usr/bin/ruby

# ruby script fragment
require 'cgi'
require 'stringio'

cgi = CGI.new()  # New CGI object
puts "Content-Type: text/plain"
puts
print '<result>'

# get uri of tx'd file (in tmp normally)
tmpfile = cgi.params['myfile'].first.path

# OR (functionally the same)
tmpfile = cgi.params['myfile'][0].path

# create a Tempfile reference
fromfile = cgi.params['myfile'].first

#displays the original file name as supplied in the form
puts fromfile.original_filename

# displays the content (mime) type e.g. text/html
puts fromfile.content_type

# create output file reference as original filename in our chosen directory
tofile = '/var/www/yourdomain.com/htdocs/r/'+fromfile.original_filename

# copy the file
# note the untaint prevents a security error
# cgi sets up an StringIO object if file < 10240
# or a Tempfile object following works for both
File.open(tofile.untaint, 'w') { |file| file << fromfile.read}
# when the page finishes the Tempfile/StringIO!) thing is deleted automatically

print '</result>'

file: file_upload.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>File upload</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  </head>
  <body>
    <form name='fileupload' enctype="multipart/form-data" 
    action='/p/file_upload.cgi' method='post'>
    <input type='file' name='myfile' size="40" />
    <input type='submit' value"Send it"/>
    </form>
  </body>
</html>
  

Unify the handling of XML records

This Ruby code creates, updates or deletes an XML record, using a hash, record handling objects, and XML to invoke the correct method.

#file: recordx_handler.rb
require 'recordx'

class RecordX_Update < RecordX
  def call(params)
    #todo: write the code to read the xml parameter string
    update_record(h)
    save_file 
  end
end

class RecordX_Create < RecordX
  def call(params)
    #todo: write the code to read the xml parameter string  
    create_record(h)
  end
end

class RecordX_Delete < RecordX
  def call(params)
    doc = Document.new(params)
    node = doc.root.elements["param[@var='id']"]
    puts node
    id = node.attributes.get_attribute('val').to_s
    delete_record(id)
    puts 'deleted record ' + id
    save_file
  end
end

class RecordX_handler
  def invoke(method, params)
    h = Hash.new
    h["create"] = RecordX_Create.new
    h["update"] = RecordX_Update.new
    h["delete"] = RecordX_Delete.new
    h[method].call(params)
  end
end

if __FILE__ == $0
  xml_method = "<method name='delete'><params><param var='id' val='17648' /></params></method>"
  doc = Document.new(xml_method)
  method = doc.root.attributes.get_attribute('name').to_s
  params = doc.root.elements['params'].to_s

  rh = RecordX_handler.new
  rh.invoke(method, params)
end


This code is intended to be called by a Ruby CGI script which can simply relay the cgi post argument to the recordx_handler object.

A simple test case using Ruby and XML - Part III

This Ruby CGI script tests a class, by reading the testdata from an XML file, then outputs the result to the web browser. Refer to parts 1 http://urltea.com/1p7h [dzone.com], and II http://urltea.com/1p7m [dzone.com]

#file: test-feed.cgi

require 'test_feed'

puts "Content-Type: text/xml"
puts

puts "<test_report>"
tf = Test_feed.new()
puts tf.plan
puts "<actual>"
tf.print('create_file', tf.tested)
puts "</actual>"
puts "</test_report>"

CGI script for collecting username and password and storing them in a database table

// CGI script for collecting username and password and storing them in a database table

#!/usr/bin/perl

# $Id$

# CGI script for collecting username and password and storing them in a database
# table. The password is encrypted with Crypt::PasswdMD5 ready for passing to
# useradd.

use strict;
use warnings;

## no critic (ValuesAndExpressions::RequireInterpolationOfMetachars)
our ($VERSION) = '$Revision$' =~ m{ \$Revision: \s+ (\S+) }xms;
## use critic

use CGI::Pretty qw(:standard -nosticky);
use DBI;
use Crypt::PasswdMD5;

# Schema for database table to store account details:
# 
# CREATE TABLE account (
#     username varchar(50) NOT NULL,
#     password varchar(50) NOT NULL,
#     date_created datetime NOT NULL
# );

my $DBNAME = 'database';
my $DBHOST = 'localhost';
my $DBPORT = 3306;
my $DBUSER = 'username';
my $DBPASS = 'password';

# Header
my $q = new CGI;
print $q->header(),
      $q->start_html(
          -title => 'New Account',
          -lang  => 'en',
      ),
      $q->h1('New Account');

my $submit    = $q->param('submit')    || q{};
my $username  = $q->param('username')  || q{};
my $password1 = $q->param('password1') || q{};
my $password2 = $q->param('password2') || q{};

my %ERROR = (
    no_username         => 'You must specify a username.',
    no_password         => 'You must specify a password.',
    password_not_twice  => 'You must specify your password twice.',
    passwords_not_match => 'Both passwords must match.',
);

my $error = (!$submit)                   ? undef                       :
            (!$username)                 ? $ERROR{no_username}         :
            (!$password1 && !$password2) ? $ERROR{no_password}         :
            (!$password1 || !$password2) ? $ERROR{password_not_twice}  :
            ( $password1 ne  $password2) ? $ERROR{passwords_not_match} :
                                           undef
            ;

if (!$submit) {
    # Form not submitted, so display empty form
    form($q);
}
elsif ($error) {
    # Show error and redisplay form
    print $q->p($error);
    form($q, $username);
}
else {
    # Enter account details into database
    my $dsn = "DBI:mysql:database=$DBNAME;host=$DBHOST;port=$DBPORT";
    my $dbh = DBI->connect($dsn, $DBUSER, $DBPASS);
    
    my $username_quoted = $dbh->quote(param('username'));
    my $password_quoted = $dbh->quote(unix_md5_crypt(param('password1')));
    
    $dbh->do("
        INSERT INTO account
        (username, password, date_created)
        VALUES ($username_quoted, $password_quoted, NOW())
    ");
    
    print $q->p('Your username and password have been recorded.');
}

# Footer
print $q->end_html();

sub form {
    my $q = shift;
    my $username = shift || q{};
    
    print start_form(),
          p('Username:', br(), textfield(
              -name  => 'username',
              -value => $username,
          )),
          p('Password:', br(), password_field(
              -name => 'password1',
          )),
          p('Password (again):', br(), password_field(
              -name => 'password2',
          )),
          p(submit(
              -name  => 'submit',
              -value => 'Submit',
          )),
          end_form();
    
    return;
}

Python - Simple Example CGI

// http://localhost/cgi-bin/example.py?variable=example

import cgi

print 'Content-type: text/html\r\n'

inputValue = cgi.FieldStorage()

if(inputValue.has_key('variable')):
  print inputValue['variable'].value

Python - Exception CGI Redirect

// Reindirizza gli errori di uno script CGI in un file random nella cartella /tmp

import cgitb; cgitb.enable(display=0, logdir='/tmp')

Python CGI script to display client's IP address

When run as a cgi script, this will print the client's IP address.

import cgi
import os

print "Content-type: text/html"
print ""

print cgi.escape(os.environ["REMOTE_ADDR"])

Decode an encoded query string in C

Here's a little function to decode part of a query string that has been encoded as per the HTML specification with %xx notation, where xx is the hexidecimal representation of a character.

Be warned that this function modifies the contents of the string you pass as the argument!

#include <stdlib.h>

char* decode_query (char* str)
{
        char*           in = str;
        char*           out = str;

        char            c = 0;
        char            decode_buffer[5] = { '0', 'x', 0, 0, 0 };

        while ((c = *in++)) {
                if (c == '%' && *in && *(in + 1)) {
                        decode_buffer[2] = *in++;
                        decode_buffer[3] = *in++;

                        c = char(strtod(decode_buffer, (char**) NULL));
                } else if (c == '+')
                        c = ' ';

                *out++ = c;
        }

        *out = 0;

        return str;
}
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS