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 11-20 of 115 total

Post to both Jaiku and Twitter

This XML code is the ProjectX API to post to both Twitter and Jaiku. This is a follow-up example from Post to Jaiku using ProjectX API [dzone.com]

xml_project = <<PROJECT
<project name='micro_blog'>
  <methods>
    <method name='post2jaiku'>
      <params>
        <param var='user' val='YourJaikuUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='location' val='YourCity'/>
        <param var='apikey' val='YourApiKey'/>
      </params>
    </method>
    <method name='post2twitter'>
      <params>
        <param var='user' val='YourTwitterUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='password' val='YourPassword'/>
      </params>
    </method>    
  </methods>
</project>"
PROJECT

Post to Jaiku using ProjectX API

This Ruby code uses the ProjectX API on rorbuilder.info to send a post to Jaiku.

Prerequisites:
1) You have a Jaiku account. see http://jaiku.com/
2) You know your Jaiku API key. see http://api.jaiku.com/

#!/usr/bin/ruby
# file: projectx_client.rb

require 'net/http'
require 'rexml/document'
include REXML

class ProjectXClient
  attr :doc
  def initialize(raw_url)
    url = URI.escape(raw_url)
    xml_data = Net::HTTP.get_response(URI.parse(url)).body
    @doc = Document.new(xml_data)
  end
  
end

if __FILE__ == $0

xml_project = <<PROJECT
<project name='jaiku'>
  <methods>
    <method name='post'>
      <params>
        <param var='user' val='YourJaikuUserName'/>
        <param var='msg' val='YourMessage'/>
        <param var='location' val='YourCity'/>
        <param var='apikey' val='YourApiKey'/>
      </params>
    </method>
  </methods>
</project>"
PROJECT
  
  pxc = ProjectXClient.new("http://rorbuilder.info/api/projectx.cgi?xml_project=" + xml_project)
  doc = pxc.doc
  puts doc
    
end



You can also pass the url including xml into the address bar and it will post to Jaiku successfully.
eg.
http://rorbuilder.info/api/projectx.cgi?xml_project="<project name='jaiku'><methods><method name='post'><params><param var='user' val='jrobertson'/><param var='msg' val='testing 223'/><param var='location' val='London'/><param var='apikey' val='5ugr6ttr754y214445'/></params></method></methods></project>"

Note:
Your api key is not in any way stored by the website rorbuilder.info.
Rorbuilder.info is a 3rd party developer website which is not part of Jaiku.com.

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]

Display a filtered list using XSLT

Following on from the post A simple XSLT example [dzone.com], this code lists all files which have the type 'rb' (equivalent to ls *.rb).

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[@type='rb']"/>
      </ul>
    </div>
    </xsl:template>
    
    <xsl:template match="records/file[@type='rb']">
      <li><xsl:value-of select="."/></li>
    </xsl:template>
    
</xsl:stylesheet>

output:
<div id='articles'>
  <ul>
    <li>projxmlhelper.rb</li>
    <li>feedpopulated.rb</li>
    <li>squrl_handler.rb</li>
    <li>password_handler.rb</li>
    <li>category.rb</li>
    <li>gwd.rb</li>
  </ul>
</div>



*update 11:58am 26-Feb*
Here's a filter I will be using in my projects

<?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">
      <xsl:if test="@type=$type">
        <li><xsl:value-of select="."/></li>
      </xsl:if>
    </xsl:template>
    
</xsl:stylesheet>

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>

Creating a simple Ruby Class documenter

This Ruby code stores the class name, method names, and method parameters from a ruby file in an XML file. I have a habit of forgetting what methods I use in my classes, with this code I should at least be able to build up a quick class browser.

#!/usr/bin/ruby

# file: ruby2xml.rb

require 'rexml/document'
include REXML

class Ruby2XML

  attr :doc
  
  def initialize(buffer)

    @outline = buffer.scan(/^class\s+(\w+)(\s+)?|def\s+(\w+)(\s+)?\(?(.*(?=\)))?/)
    @doc = Document.new
    @doc.add_element('ruby')
    o_class = Element.new('class')
    o_class.add_attribute('name', get_class_name)
    o_methods = Element.new('methods')
    
    #get the methods
    1.upto(get_method_count) {|i| o_methods.add_element(add_method(@outline[i])) }
    o_class.add_element(o_methods)
    @doc.root.add_element o_class

  end
  
  private # everything below this point is private
  
  def get_class_name()
    @outline[0][0]
  end
  
  def get_method_count
    mc = -1
    @outline.each {|m| mc += 1}
    mc 
  end
  
  def add_method(amethod)
    o_method = Element.new('method')
    o_method.add_attribute('name',amethod[2]) #get the method name
    o_params = Element.new('params')

    if amethod[4] then # get the parameter names
      amethod[4].split(',').each {|a| o_params.add_element(add_param(a.strip))}
    end
    
    o_method.add_element(o_params)    
    o_method
  end
  
  def add_param(param)
    o_param = Element.new('param')
    o_param.text = param
    o_param
  end
      
end

if __FILE__ == $0

  buffer = File.new('ruby2xml.rb').read
  rx2 = Ruby2XML.new(buffer)
  
  file = File.new('ruby2xml.xml','w')
  file.puts rx2.doc
  file.close

end


Note: This is just my first attempt at building some kind of Ruby code documenter, but it should be good enough for my needs at the moment.

output
<ruby>
  <class name='Ruby2XML'>
    <methods>
      <method name='initialize'><params><param>buffer</param></params></method>
      <method name='get_class_name'><params/></method>
      <method name='get_method_count'><params/></method>
      <method name='add_method'><params><param>amethod</param></params></method>
      <method name='add_param'><params><param>param</param></params></method>
    </methods>
  </class>
</ruby>

ProjectX client-side code

This Ruby code uses a unified XML format to create a password record on a web server. It's intended to be run as a batch file which gets called from another Ruby application called maintain_projectx which gets called from a cronjob.

In this example the password is stored on the server not for authentication but simply to provide a reminder service in the event the user forgets it.

require 'net/http'
require 'rexml/document'
include REXML

class ProjectXClient
  attr :doc
  def initialize(raw_url)
    url = URI.escape(raw_url)
    xml_data = Net::HTTP.get_response(URI.parse(url)).body
    @doc = Document.new(xml_data)
  end
  
end

if __FILE__ == $0

  xml_project = <<PROJECT
  <project name='password'>
    <method name='create'>
      <params>
        <param var='password' val='p6789c'/>
        <param var='title' val='hotmail'/>
      </params>
    </method>
  </project>
PROJECT
  
  pxc = ProjectXClient.new("http://yourdomain.com/p/projectx.cgi?xml_project=" + xml_project)
  doc = pxc.doc
  puts doc
    
end


output -what's returned from the server is an XML response containing a result. The result echos the method executed and the output from that method, which in this instance is the xml record node 'entry'.
<result method='rtn_create'>
  <append id='19367'>
    <entry id='19367'>
      <password>p6789c</password>
      <title>hotmail</title>
      <description/>
    </entry>
  </append>
</result>


Converting XHTML to XML

Based on the code from 'Convert from HTML to XML with HTML Tidy', this code will read an xhtml file and extract text to gallery.xml as instructed by xhtml2xml.xml

#!/usr/bin/ruby
  
  require 'tidy'
  require 'projxslt'
  
  FILE_PATH = "../"
  
  class Xhtml2Xml
    def convert()
      project = 'xhtml2xml'
      filein = 'xhtml2xml.xml'
      filehtml = 'gallery.html'
      filexml = 'gallery_xhtml.xml'
      xslfile_temp = 'gallery.xsl'
      xslfile = 'xhtml2xml.xsl'
      fileout = 'gallery.xml'
      tidy_config = 'tidy.txt'
      
      project_path = FILE_PATH + project + '/'
      tidy_config_path = project_path + tidy_config
      filein_path = project_path + filein
      filehtml_path = project_path + filehtml
      filexml_path = project_path + filexml
      xslfile_temp_path = project_path + xslfile_temp
      xslfile_path = project_path + xslfile
      fileout_path = project_path + fileout
      
      Tidy.path = '/usr/lib/libtidy.so'

      file = File.new(filehtml_path,'r')
      buffer = file.read
      xml = Tidy.open(:show_warnings=>true) do |tidy|
        tidy.options.output_xml = true
        tidy.load_config(tidy_config_path)
        puts tidy.options.show_warnings
        xml = tidy.clean(buffer)
        puts tidy.errors
        puts tidy.diagnostics
        xml
      end
      
      #strip out the html document type declaration and save the file
      html_declaration = xml[/<!([^>]*>){2}/]
      save_file(filexml_path, xml.gsub(html_declaration,'<html>'))    
      transform(filein_path, xslfile_path, xslfile_temp_path)
      transform(filexml_path, xslfile_temp_path, fileout_path)
      
    end
    
    def transform(xml_filepath, xsl_filepath, save_filepath)
      pxsl = Projxslt.new(xml_filepath, xsl_filepath)
      outfile = pxsl.transform
      save_file(save_filepath, outfile)
    end
    
    def save_file(filepath, buffer)
      file = File.new(filepath,'w') 
      file.puts buffer
      file.close
    end    
  end
  
  if __FILE__ == $0
    h2x = Xhtml2Xml.new()
    h2x.convert()
  end

file: xhtml2xml.xml
<root element="gallery">
  <summary>
    <field element="title" xpath="head/title"/>
  </summary>
  <record xpath="body/center/table/tr/td" element="photo">
    <field xpath="font/br[3]/preceding-sibling::text()[1]" element="title"></field>
    <field xpath="/html/body/table/tr/td[2]/font/br[3]/preceding-sibling::text()[1]" element="date"></field>
    <field xpath="font/br[1]/preceding-sibling::text()[1]" element="image"></field>
    <field xpath="font/br[2]/preceding-sibling::text()[1]" element="description"></field>
  </record>
</root>

file:xhtml2xml.xsl (transforms the file xhtml2xml.xml to file gallery.xsl)
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="root">
    <xsl:variable name="colon"><xsl:text>:</xsl:text></xsl:variable>
    
    <xsl:element name="xsl:stylesheet">
      <xsl:attribute name="xmlns{$colon}xsl">
        <xsl:text>http://www.w3.org/1999/XSL/Transform</xsl:text>
      </xsl:attribute>
      <xsl:attribute name="version">
        <xsl:text>1.0</xsl:text>
      </xsl:attribute><xsl:text>
      </xsl:text>

<xsl:element name="xsl:output">
  <xsl:attribute name="method">
    <xsl:text>xml</xsl:text>
  </xsl:attribute>
  <xsl:attribute name="indent">
    <xsl:text>yes</xsl:text>
  </xsl:attribute>
</xsl:element><xsl:text>

</xsl:text>

<xsl:element name="xsl:template">
      <xsl:attribute name="match">
        <xsl:text>html</xsl:text>
      </xsl:attribute><xsl:text>
</xsl:text>
      <xsl:element name="{@element}">
      <xsl:apply-templates select="summary"/>

      <xsl:element name="xsl{$colon}for-each">
        <xsl:attribute name="select">
          <xsl:value-of select="record/@xpath"/>
        </xsl:attribute><xsl:text>
    </xsl:text>              

  <xsl:for-each select="record/field">
    <xsl:element name="xsl:variable">
      <xsl:attribute name="name">
        <xsl:value-of select="@element"/>
      </xsl:attribute>
      <xsl:attribute name="select">
        <xsl:value-of select="@xpath"/>
      </xsl:attribute>
    </xsl:element><xsl:text>
    </xsl:text>
  </xsl:for-each>
<xsl:text>
    </xsl:text>

        <xsl:element name="{record/@element}">
       <xsl:for-each select="record/field">
              <xsl:element name="{@element}"><xsl:text>
        </xsl:text>
            <xsl:element name="xsl:value-of">
              <xsl:attribute name="select"><xsl:text>normalize-space($</xsl:text>
                <xsl:value-of select="@element"/>
                <xsl:text>)</xsl:text>                
              </xsl:attribute>
          </xsl:element>  <xsl:text>
      </xsl:text>
          </xsl:element>

    </xsl:for-each>
</xsl:element><xsl:text>
  </xsl:text>
</xsl:element><xsl:text>
</xsl:text>
 
  </xsl:element>
</xsl:element> <!-- template match -->
</xsl:element> <!-- gallery -->
  </xsl:template> 


<xsl:template match="summary/field"><xsl:text>
</xsl:text>
      <xsl:element name="xsl:element">
        <xsl:attribute name="name">
          <xsl:value-of select="@element"/>
        </xsl:attribute><xsl:text>
</xsl:text>
        <xsl:element name="xsl:value-of">
          <xsl:attribute name="select">
            <xsl:value-of select="@xpath"/>
          </xsl:attribute><xsl:text>
</xsl:text>
        </xsl:element><xsl:text>
</xsl:text>
      </xsl:element><xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>

output: gallery.xml (this file is the product of gallery_xhtml.xml and gallery.xsl)
<?xml version="1.0"?>
<gallery>
  <title>Journey to Windsor</title>
  <photo>
    <title>Windsor Castle</title>
    <date>July 2003</date>
    <image>dscn0824.jpg</image>
    <description>
      A bright, red mailbox inside the castle. It seems oddly familiar in an historic setting.
    </description>
  </photo>
</gallery>

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]
« Newer Snippets
Older Snippets »
Showing 11-20 of 115 total