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

About this user

James Robertson http://www.r0bertson.co.uk

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

A simple XHTML submit form for ProjectX

Preparing ProjectX API requests through the browser's address bar can get quite messy, however inputting the request through a simple form makes it much easier to read.

<!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>ProjectX API</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  </head>
  <body>
    <h1>ProjectX API form</h1>
    <p>Enter the Project API XML to send a request to the server.</p>
    <form action="http://rorbuilder.info/api/projectx.cgi" method="post" id="projectx_form">
    <fieldset><legend>xml_project</legend><textarea id="xml_project" name="xml_project" cols="104" rows="20"></textarea></fieldset>
    <div><button type="submit">Submit</button></div>
    </form>
  <p>
    <a href="http://validator.w3.org/check?uri=referer"><img
        src="http://www.w3.org/Icons/valid-xhtml10"
        alt="Valid XHTML 1.0 Strict" height="31" width="88" style="float:right;  border:0 "/></a>
  </p>
  <p style="clear:float">last updated: 13th April 2008</p>
  
  </body>
</html>


The web page can be seen at http://rorbuilder.info/r/projectx-api/index.html
The following XML request value when submitted should return an XML result containing the results and the method executed.
<project name='whiteboardqueue'>
  <methods>
    <method name='get_user_id'>
      <params/>
    </method>
  </methods>
</project>

eg.
<result method="rtn_get_user_id">
  <get_user_id>36539</get_user_id>
</result>

Format Ruby code in HTML

This code uses the Ruby gem 'syntax' to create an XML file containing the HTML tags around the code, which is then transformed into an HTML file. The working example was first built using coding examples from Howto format ruby code for blogs [wolfman.com] and Formatting Ruby and HTML code for blog posting [blogspot.com]

#!/usr/bin/ruby

#file: ruby2html.rb 

require 'rubygems'
require 'syntax/convertors/html'
require 'projxslt' # <- this is my own class to do an XSLT transform 
require 'rexml/document'
include REXML

class Ruby2Html
  def initialize(rubyfile, htmlfile)
    code = File.read(rubyfile)
    convertor = Syntax::Convertors::HTML.for_syntax "ruby"
    code_html = convertor.convert(code)
    
    tempfile = '../temp/ruby2html.xml'
    xslfile = '../ruby2html/ruby2html.xsl'
    save_file(tempfile, code_html)
    
    px = Projxslt.new(tempfile, xslfile)
    buffer = px.transform()
    save_file(htmlfile, buffer)
    
  end
  
  def save_file(filename, buffer)
    file = File.new(filename, 'w')
    file.puts buffer
    file.close
  end
end

if __FILE__ == $0
  r2h = Ruby2Html.new('ruby2html.rb', '../temp/ruby2html.html')
  puts 'completed'
end

file: ruby2html.xsl
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns="http://www.w3.org/1999/xhtml"
                version="1.0">

  <xsl:output method="html" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
          doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
          encoding="ISO-8859-1"/> 

	<xsl:template match="/">
	<xsl:element name="html">

        <head>
          <title>Sample code</title>
          <link rel="stylesheet" type="text/css" href="ruby2html.css" />
	</head>

	<body>
          <div id="wrap">
          <xsl:apply-templates />
          </div>
	</body> 

	</xsl:element>
	</xsl:template>

	<xsl:template match="pre">
	  <xsl:copy-of select="."/>
	</xsl:template>

</xsl:stylesheet>

Here's the output from the formatted Ruby HTML code [twitxr.com]

Referemce: Syntax Manual [rubyforge.org]

A simple XSLT example

Produce a list of filenames using XML and XSLT

file: dir.xsl
<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      
    <xsl:template match="dir">
    <div id="articles">
      <ul>
      <xsl:apply-templates select="records/file"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file">
      <li><xsl:value-of select="."/></li>
    </xsl:template>
    
</xsl:stylesheet>


file: dir.xml
<dir>
  <summary>
    <directory>./</directory>
  </summary>
  <records>
    <file type='xml'>mjournal.xml</file>
    <file type='rb'>projxmlhelper.rb</file>
    <file type='rb'>feedpopulated.rb</file>
    <file type='rb'>squrl_handler.rb</file>
    <file type='cgi'>snurl.cgi</file>
    <file type='cgi'>dynalert.cgi</file>
    <file type='rb'>password_handler.rb</file>
    <file type='rb'>category.rb</file>
    <file type='rb'>gwd.rb</file>
    <file type='cgi'>new-journal-entry.cgi</file>
  </records>
</dir>


then transforming the XML with the command 'xsltproc dir.xsl dir.xml' produces the following:
output:
<div id='articles'>
  <ul>
    <li>mjournal.xml</li>
    <li>projxmlhelper.rb</li>
    <li>feedpopulated.rb</li>
    <li>squrl_handler.rb</li>
    <li>snurl.cgi</li>
    <li>dynalert.cgi</li>
    <li>password_handler.rb</li>
    <li>category.rb</li>
    <li>gwd.rb</li>
    <li>new-journal-entry.cgi</li>
  </ul>
</div>

Save a Ruby source text file to XML.

This code will output a text file as an XML file which can later be transformed into an HTML file using a back-end XSLT processor called Gorg.

#!/usr/bin/ruby 

#file: rubytxt2xml.rb

require 'rexml/document'
include REXML

class RubyTxt2XML
  
  def rubytxt2xml(h)
    h[:infilepath] = './' if h[:infilepath].nil?
    h[:outfilepath] = './' if h[:outfilepath].nil?
    h[:xmlfile] = h[:sourcefile][/^(.*)\.\w+$/,1] + '.xml' if h[:xmlfile].nil?
    buffer = File.new(h[:infilepath] + h[:sourcefile],'r').read
    
    doc = Document.new
    doc.add_element('ruby_txt')
    body = Element.new('source')
    body.text = CData.new(buffer)
    doc.root.add_element(body)
    
    file = File.new(h[:outfilepath] + h[:xmlfile],'w')
    file.puts doc
    file.close
    
  end
end

if __FILE__ == $0
  rt2x = RubyTxt2XML.new
  rt2x.rubytxt2xml(:sourcefile  => 'rubytxt2xml.rb')
end

output:
<ruby_txt>
  <source>
    <![CDATA[
      #!/usr/bin/ruby 

      #file: rubytxt2xml.rb

      require 'rexml/document'
      include REXML

      class RubyTxt2XML
        
        def rubytxt2xml(h)
          h[:infilepath] = './' if h[:infilepath].nil?
          h[:outfilepath] = './' if h[:outfilepath].nil?
          h[:xmlfile] = h[:sourcefile][/^(.*)\.\w+$/,1] + '.xml' if h[:xmlfile].nil?
          buffer = File.new(h[:infilepath] + h[:sourcefile],'r').read
          
          doc = Document.new
          doc.add_element('ruby_txt')
          body = Element.new('source')
          body.text = CData.new(buffer)
          doc.root.add_element(body)
          
          file = File.new(h[:outfilepath] + h[:xmlfile],'w')
          file.puts doc
          file.close
          
        end
      end

      if __FILE__ == $0
        rt2x = RubyTxt2XML.new
        rt2x.rubytxt2xml(:sourcefile  => 'rubytxt2xml.rb')
      end
    ]]>
  </source>
</ruby_txt>

Convert from HTML to XHTML with HTML Tidy

This HTML Tidy example converts an html file into an xml file.

tidy -asxhtml -numeric < index.html > index.xml


example found from Tip: Convert from HTML to XML with HTML Tidy [ibm.com]

Tidy with Ruby

Ruby interface to HTML Tidy Library Project (tidy.sf.net).

  require 'tidy'
  Tidy.path = '/usr/lib/libtidy.so'
  html = '<html><title>title</title>Body</html>'
  xml = Tidy.open(:show_warnings=>true) do |tidy|
    tidy.options.output_xml = true
    puts tidy.options.show_warnings
    xml = tidy.clean(html)
    puts tidy.errors
    puts tidy.diagnostics
    xml
  end
  puts xml


output
true
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 7 - Warning: plain text isn't allowed in <head> elements
Info: Document content looks like XHTML 1.0 Transitional
2 warnings, 0 errors were found!

<html>
<head>
<meta name="generator"
content="HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org" />
<title>title</title>
</head>
<body>Body</body>
</html>



Note: Couldn't get it to run on Ubuntu version 7.10 or 7.04 (LoadError: no such file to load -- tidy
), however it ran fine on Gentoo.

reference: http://tidy.rubyforge.org/

*update 18-Mar-08 16:15*
I got it working on Ubuntu I simply needed to add - require 'rubygems'

Encode simple passwords

This code was used to demonstrate how to translate easy to remember simple (weak) passwords into more difficult to guess (strong) passwords. Example: Using Gmail I like an easy to remember password, I submit the password 'jr123' to the password_lookup.html page and what's returned to me is a stronger password 'NCC2SI1T'.

file: passwd_lookup.rb (generates an xml file containing an alphanumeric index with corresponding cryptic values)
class PasswordLookup

  def initialize()
    chars =  (0..9).to_a  + Array.new(7) + ('A'..'Z').to_a + Array.new(6) + ('a'..'z').to_a 
    @chars = (0..9).to_a  + ('A'..'Z').to_a + ('a'..'z').to_a 
    @doc = Document.new()
    root = Element.new('codes')
    @doc.add_element(root)

    chars.each do |char|
      node = Element.new('code')
      if not char.nil? 
        node.attributes['index'] = char
        node.attributes['value'] = get_random_chars(2)
      end
      root.add_element(node)
    end
    puts root
  end

  
  def save(filepath)
    file = File.new(filepath,'w')
    file.puts @doc
    file.close
  end
        
  def get_random_chars(vword_size)
    newpass = Array.new(rand(vword_size) + 1, '').collect{@chars[rand(@chars.size)]}.join
    # return the encryption providing it doesn't already exist in the lookup table.
    if not /value=\'#{newpass}\'/.match @doc.root.elements.to_a.to_s 
     return newpass 
    else
     return get_random_chars(vword_size) 
    end

  end
  
  private :get_random_chars
  
end


output extract: (codes - see also http://rorbuilder.info/pl/codes)
<codes>
<code value='4h' index='a'/><code value='B' index='b'/><code value='m' index='c'/>
<code value='qf' index='d'/>
</codes>


file: password_lookup.js
var t;
var m_doc;

function loadXml() {
  url = 'http://rorbuilder.info/pl/codes';
  m_doc = XML.load(url);
}

function getCode(val,i) {
  pos = val.charCodeAt(i) - 48;
  node = m_doc.documentElement.childNodes[pos]
  return node.getAttribute('value');
}

function timed_update(keyCode,  val) {
  if (val.length > 0 && ((keyCode > 40) || (keyCode == 8)) ) {
    clearTimeout(t);
    t = setTimeout("revealCode('" + val + "')", 1000);
  }
  else
  {  
    o = document.getElementById('out1');
    if (val.length <= 0 && o.value.length > 0) {
      o.value = '';
    }
  }
  
}

function revealCode(val) {
  var iEnd = val.length;
  var newcode = '';
  for (i=0;i<iEnd;i++) {
      
    var codex = getCode(val,i);
    newcode += codex;
  }
  update(newcode);
}

function update(val){
  o = document.getElementById('out1');
  o.value = val;
  /*var o_copied = document.getElementById('out1').createTextRange();
  o_copied.exeCommand("Copy");*/
}


file: password_lookup.html
  <body onload="loadXml()">
    <h1>Password lookup</h1>
    <dl>
    <dt><label for="in1">Enter password:</label></dt>    
    <dd><input type="text" name="in1" id="in1" value="" 
  onkeyup="timed_update(event.keyCode, this.value)" /></dd>
    
    <dt><label for="out1">Generated password</label></dt>
    <dd><input type="text" name="out1" id="out1" value=""/></dd>
    <dd><input type="button" name="clear1" id="clear1" onclick="clearPassword()" value="clear"/></dd>

    </dl>
    <p>see also: <a href="codes.xml" title="password code lookup table">codes.xml</a></p>
  </body>


Try out the encode a simple password demo [rorbuilder.info].

see also: Reading an XML file usng JavaScript [snippets.dzone.com]

Reading an XML file using JavaScript

Reads an xml file using JavaScript from a web page. Files used: loadxml.js (main script), readxml.js (client script), and readxml.html. The code for loadxml.js was copied from the article JavaScript and XML [devarticles.com]

file: loadxml.js
  XML.load = function(url) {
    var xmldoc = XML.newDocument();
    xmldoc.async = false;  
    xmldoc.load(url);
    return xmldoc;  
  };


XML.newDocument = function(rootTagName, namespaceURL) {
    if (!rootTagName) rootTagName = "";
    if (!namespaceURL) namespaceURL = "";

    if (document.implementation && document.implementation.createDocument) {
        // This is the W3C standard way to do it
        return document.implementation.createDocument(namespaceURL, 
                       rootTagName, null);
    }
    else { // This is the IE way to do it
        // Create an empty document as an ActiveX object
        // If there is no root element, this is all we have to do
        var doc = new ActiveXObject("MSXML2.DOMDocument");

        // If there is a root tag, initialize the document
        if (rootTagName) {
            // Look for a namespace prefix
            var prefix = "";
            var tagname = rootTagName;
            var p = rootTagName.indexOf(':');
            if (p != -1) {
                prefix = rootTagName.substring(0, p);
                tagname = rootTagName.substring(p+1);
            }

            // If we have a namespace, we must have a namespace prefix
            // If we don't have a namespace, we discard any prefix
            if (namespaceURL) {
                if (!prefix) prefix = "a0"; // What Firefox uses
            }
            else prefix = "";

            // Create the root element (with optional namespace) as a
            // string of text
            var text = "<" + (prefix?(prefix+":"):"") + tagname +
                (namespaceURL
                 ?(" xmlns:" + prefix + '="' + namespaceURL +'"')
                 :"") +
                "/>";
            // And parse that text into the empty document
            doc.loadXML(text);
        }
        return doc;
    }
}; 


file: readxml.js
function readXmlFile() {
  url = 'http://rorbuilder.info/pl/test123';

  doc = XML.load(url);
  alert(doc.documentElement.firstChild.nextSibling.firstChild.nodeValue);
}


file: readxml.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>Read an XML file</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript" src="js/loadxml.js"/>
    <script type="text/javascript" src="js/readxml.js"/>
  </head>

  <body>
    <h1>ReadXML</h1>
    <p>
       If all goes well you should see an alert box display the message 'testing 123'
   </p>
    <p>Press the 'go' button to read the xml file '<a href="test123">test123</a>' 
       from the web server. 
       <input type="button" onclick="readXmlFile()" value="go"/>
    </p>

    
  </body>
</html>


Note: To avoid the cross-site security error message 'permission denied', store all the files on the same web server.

To test the above code try out the demo to read the xml file [rorbuilder.info].

Zebra stripes on rows using XSLT

Using XSL every 2nd row will contain the class named 'stripe'.
  <xsl:element name="li">
        <xsl:if test="(position() mod 2) != 1">
          <xsl:attribute name="class"><xsl:text>stripe</xsl:text></xsl:attribute>
	</xsl:if>
  </xsl:element>

Adding CSS style to buttons

This HTML and CSS code shows how to customise buttons in a restful way. Source: http://particletree.com/features/rediscovering-the-button-element/
<div class="buttons">
    <button type="submit" class="positive">
        <img src="/images/icons/tick.png" alt=""/> 
        Save
    </button>

    <a href="/password/reset/">
        <img src="/images/icons/textfield_key.png" alt=""/> 
        Change Password
    </a>

    <a href="#" class="negative">
        <img src="/images/icons/cross.png" alt=""/>
        Cancel
    </a>
</div>

/* BUTTONS */

.buttons a, .buttons button{
    display:block;
    float:left;
    margin:0 7px 0 0;
    background-color:#f5f5f5;
    border:1px solid #dedede;
    border-top:1px solid #eee;
    border-left:1px solid #eee;

    font-family:"Lucida Grande", Tahoma, Arial, Verdana, sans-serif;
    font-size:100%;
    line-height:130%;
    text-decoration:none;
    font-weight:bold;
    color:#565656;
    cursor:pointer;
    padding:5px 10px 6px 7px; /* Links */
}
.buttons button{
    width:auto;
    overflow:visible;
    padding:4px 10px 3px 7px; /* IE6 */
}
.buttons button[type]{
    padding:5px 10px 5px 7px; /* Firefox */
    line-height:17px; /* Safari */
}
*:first-child+html button[type]{
    padding:4px 10px 3px 7px; /* IE7 */
}
.buttons button img, .buttons a img{
    margin:0 3px -3px 0 !important;
    padding:0;
    border:none;
    width:16px;
    height:16px;
}

Adding colour to the buttons - Colour is used like a traffic light system, green for go (positive), red for stop (negative, think about this for a moment), and blue which isn't a traffic light (neutral, a miscellaneous item)
/* STANDARD */

button:hover, .buttons a:hover{
    background-color:#dff4ff;
    border:1px solid #c2e1ef;
    color:#336699;
}
.buttons a:active{
    background-color:#6299c5;
    border:1px solid #6299c5;
    color:#fff;
}

/* POSITIVE */

button.positive, .buttons a.positive{
    color:#529214;
}
.buttons a.positive:hover, button.positive:hover{
    background-color:#E6EFC2;
    border:1px solid #C6D880;
    color:#529214;
}
.buttons a.positive:active{
    background-color:#529214;
    border:1px solid #529214;
    color:#fff;
}

/* NEGATIVE */

.buttons a.negative, button.negative{
    color:#d12f19;
}
.buttons a.negative:hover, button.negative:hover{
    background:#fbe3e4;
    border:1px solid #fbc2c4;
    color:#d12f19;
}
.buttons a.negative:active{
    background-color:#d12f19;
    border:1px solid #d12f19;
    color:#fff;
}

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