SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
Ruby for Java
programmers
Ugo Cei
Sourcesense
u.cei@sourcesense.com
Who should attend this talk
• Java programmers wishing to know how to include Ruby
  code in Java programs or vice-versa.
• Ruby programmers wishing for the same.


     Who should NOT attend this talk
• Java programmers wishing to learn more about the Ruby
  programming language.
• This is not a talk about the differences between Java and
  Ruby.




                                       Ugo Cei: “Ruby for Java Programmers”
Agenda
• Why?
• How?
• Bridges
• JRuby
• XML-RPC
• SOAP
• Demos




                     Ugo Cei: “Ruby for Java Programmers”
What’s in it for me?




               Ugo Cei: “Ruby for Java Programmers”
Shameless Plug: The Open Source Zone




            http://oszone.org
                            Ugo Cei: “Ruby for Java Programmers”
Shameless Plug: The Open Source Zone




            http://oszone.org
                            Ugo Cei: “Ruby for Java Programmers”
Shameless Plug: Evil or Not?




       http://evilornot.info
                          Ugo Cei: “Ruby for Java Programmers”
Shameless Plug: Evil or Not?




if /<title>(.+)</title>/ ...                          Search?

                     http://evilornot.info
                                        Ugo Cei: “Ruby for Java Programmers”
“The era of islands is over for most
development scenarios. You don't have to
make one definitive choice. Instead, you
get to hog all the productivity you can for
the common cases, then outsource the
bottlenecks to existing packages in faster
languages or build your own tiny extension
when it's needed.”

   David Heinemeier Hansson, Sep 13, 2006
                           Ugo Cei: “Ruby for Java Programmers”
How?




       Ugo Cei: “Ruby for Java Programmers”
RubyJavaBridge
• http://arton.no-ip.info/collabo/backyard/?RubyJavaBridge
• Follow the instructions in readme.txt and on the website
  and it should work (even on Intel Macs).
• Encapsulate you Java code in high-level methods and
  classes to hide 3rd party libraries and Java idiosyncrasies
  from Ruby as much as possible.




                                        Ugo Cei: “Ruby for Java Programmers”
Sample Java Code
• Uses ROME (https://rome.dev.java.net).


public class Fetcher {
	      public static SyndFeed fetch(String url) throws Exception {
	       	      URL feedUrl = new URL(url);
	       	      FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
	       	      FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
	       	      SyndFeed feed = fetcher.retrieveFeed(feedUrl);
	       	      return feed;
	      }
}




                                                   Ugo Cei: “Ruby for Java Programmers”
Client Ruby Code
 require 'rjb'

 Rjb::load('.:rome-0.7.jar:rome-fetcher-0.7.jar:jdom.jar:jdom.jar', [])

 fetcher = Rjb::import('Fetcher')
 feed = fetcher.fetch(ARGV[0])
 print feed.getTitle, “n”
 entries = feed.getEntries.iterator
 while entries.hasNext do
   entry = entries.next
   print quot;#{entry.getPublishedDate.toString} #{entry.getTitle}nquot;
 end
• No mapping from Java iterators to Ruby loops.
• No date type conversions.
• No support for JavaBean properties.

                                                            Ugo Cei: “Ruby for Java Programmers”
YAJB
• http://www.cmt.phys.kyushu-u.ac.jp/~M.Sakurai/cgi-bin/fw/
  wiki.cgi?page=YAJB
• Same caveats and limitations as for RJB.




                                      Ugo Cei: “Ruby for Java Programmers”
Client Ruby Code
require 'yajb/jbridge'
include JavaBridge

JBRIDGE_OPTIONS = {
  :classpath => '.:rome-0.7.jar:rome-fetcher-0.7.jar:jdom.jar:jdom.jar'
}

jimport quot;Fetcherquot;

feed = :Fetcher.jclass.fetch(ARGV[0])
print feed.getTitle, quot;nquot;
entries = feed.getEntries.iterator
while entries.hasNext do
  entry = entries.next
  print quot;#{entry.getPublishedDate.toString} #{entry.getTitle}nquot;
end



                                                          Ugo Cei: “Ruby for Java Programmers”
Making a Simple Java Class
 require 'yajb/jbridge'
 require 'yajb/jlambda'

 include JavaBridge

 c = JClassBuilder.new(quot;MyClassquot;)
 c.add_field(quot;private int num;quot;)
 c.add_constructor(quot;public AAA(int a) {num = a;}quot;)
 c.add_method(quot;public int square() { return num * num;}quot;)
 puts quot;Simple class: #{c.new_instance(5).square}quot;



• Uses javassist: http://www.csg.is.titech.ac.jp/~chiba/
  javassist/index.html



                                                       Ugo Cei: “Ruby for Java Programmers”
Implementing an Interface
jimport quot;java.util.*quot;
c = JClassBuilder.new(quot;NumCompquot;)
c.add_interface(quot;java.util.Comparatorquot;) # must be full qualified class name
c.add_method(<<'JAVA')
public int compare(Object o1, Object o2) do
  int i1 = ((Number)o1).intValue();
  int i2 = ((Number)o2).intValue();
  return i2-i1;
end
JAVA
sample = [9,1,8,2,7,3,6,4,5,0,10]
list = :ArrayList.jnew
sample.each {|i|
  list.add( i )
}
:Collections.jclass.sort(list, c.new_instance)
p quot;Sort:quot;,list.toArray

                                                       Ugo Cei: “Ruby for Java Programmers”
Using SWIG
• http://www.swig.org
• Jakarta POI, nifty library for manipulating Microsoft OLE 2
  Compound Document formats (Office files) uses SWIG to
  provide Ruby bindings.
• POI compiled using gcj and Ruby bindings generated
  using SWIG.
• http://jakarta.apache.org/poi/poi-ruby.html




                                        Ugo Cei: “Ruby for Java Programmers”
JRuby
• http://jruby.sourceforge.net/
• http://jruby.codehaus.org/
• JRuby is not a bridge between Java and Ruby but a full-
  featured Ruby interpreter written in 100% Java.
• Gives Ruby code instant access to all Java libraries.
• Cannot load Ruby extensions written in C.
• “Almost” Mostly able to run RubyGems and Rails.
• Quick development pace.
• Still slow compared to C Ruby, but quoting Charles O.
  Nutter: “I think it's now very reasonable to say we could
  beat C Ruby performance by the end of the year.”


                                       Ugo Cei: “Ruby for Java Programmers”
JRuby Client Code
 require 'java'

 include_class 'Fetcher'

 feed = Fetcher.fetch(ARGV[0])

 feed.entries.each do | entry |
   p quot;#{entry.publishedDate} #{entry.title}quot;
 end


• Can use “each” on Java collections.
• Date type conversion.
• Full support for JavaBean properties.


                                               Ugo Cei: “Ruby for Java Programmers”
Calling Ruby Methods
• demo1.rb

class Demo1
 def foo
   print 'bar'
 end
end


• Demo1.java
IRuby runtime = Ruby.getDefaultInstance();
runtime.loadFile(new File(quot;ruby/demo1.rbquot;), false);
RubyClass rb = runtime.getClass(quot;Demo1quot;);
IRubyObject obj = rb.newInstance(new RubyObject[0]);
obj.callMethod(quot;fooquot;);


                                                Ugo Cei: “Ruby for Java Programmers”
Using the Bean Scripting Framework
• The Bean Scripting Framework, when used with JRuby,
  will allow you more conveniently to pass your own Java
  objects to your JRuby script. You can then use these
  objects in JRuby, and changes will affect your Java
  program directly.

    BSFManager.registerScriptingEngine(quot;rubyquot;,
        quot;org.jruby.javasupport.bsf.JRubyEnginequot;, new String[] { quot;rbquot; });
    BSFManager manager = new BSFManager();
    JLabel mylabel = new JLabel();
    manager.declareBean(quot;labelquot;, mylabel, JLabel.class);
    manager.exec(quot;rubyquot;, quot;(java)quot;, 1, 1, quot;$label.setText(quot;This is a test.quot;)quot;);



                                                      Ugo Cei: “Ruby for Java Programmers”
Name Clashes
 import_class ‘java.lang.String’
 import_class ‘java.net.URI’
• This won’t work as it conflicts with Ruby’s String and URI
  classes.
• Solution: use a module.
 module Java
     import_class ‘java.lang.String’
     import_class ‘java.net.URI’
 end
 ...
 uri = Java::URI.new(‘http://example.com/’)

• Or remap names:
 include_class(quot;java.lang.Exceptionquot;) {|p,n| quot;Jquot; + n }

                                                         Ugo Cei: “Ruby for Java Programmers”
Running Ruby on Rails




               Ugo Cei: “Ruby for Java Programmers”
Running Camping




• http://jruby.codehaus.org/The+JRuby+Tutorial+Part+2+-
  +Going+Camping


                                     Ugo Cei: “Ruby for Java Programmers”
Using the JDBC AR Adapter
jruby $JRUBY_HOME/bin/gem install ActiveRecord-JDBC --no-ri --no-rdoc

• As of 0.2.0 works for:
  • MySQL
  • PostgreSQL
  • Oracle
  • HSQLDB
  • Microsoft SQL Server
  • DB2
  • Apache Derby
  • FireBird

                                                Ugo Cei: “Ruby for Java Programmers”
Using the JDBC AR Adapter


adapter: jdbc
driver: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/dbname
username: admin
password: secret




                                          Ugo Cei: “Ruby for Java Programmers”
XML-RPC
• Pro: Established technology.
• Pro: No need to use bridge code or special interpreters.
• Con: Separate processes => must take network latency
  and failures into account.
• Con: Overhead of HTTP communication, XML parsing,
  marshalling...
• Need to convert types to something that XML-RPC is able
  to understand, i.e.strings, numbers, dates, Vectors,
  Hashtables and little else.




                                     Ugo Cei: “Ruby for Java Programmers”
XML-RPC Java Server
• Uses Apache XML-RPC.

public class RPCFetcher {

  public static void main(String args[]) throws Exception {
    WebServer server = new WebServer(8080);
    server.addHandler(quot;$defaultquot;, new RPCFetcher());
    server.start();
  }

  // Continued...




                                                    Ugo Cei: “Ruby for Java Programmers”
XML-RPC Java Server
public Vector fetch(String url) throws Exception {
  URL feedUrl = new URL(url);
  FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
  FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
  SyndFeed feed = fetcher.retrieveFeed(feedUrl);
  Vector items = new Vector();
  for (Iterator it = feed.getEntries().iterator() ; it.hasNext() ; ) {
      SyndEntry entry = (SyndEntry) it.next();
      Hashtable map = new Hashtable();
      map.put(quot;linkquot;, entry.getLink());
      map.put(quot;titlequot;, entry.getTitle());
      map.put(quot;publishedDatequot;, entry.getPublishedDate());
      items.add(map);
  }
  return items;
}


                                           Ugo Cei: “Ruby for Java Programmers”
XML-RPC Ruby Client


require 'xmlrpc/client'
server = XMLRPC::Client.new 'localhost', '/', 8080
entries = server.call('fetch', 'http://agylen.com/feed')
entries.each do | entry |
 p quot;#{entry['publishedDate'].to_time} #{entry['title']}quot;
end




                                                       Ugo Cei: “Ruby for Java Programmers”
SOAP
• Complex and heavyweight, but most of the complexity is
  hidden by tools.
• WSDL service description can be automatically generated
  from server code.
• Ruby’s SOAP library provides what is necessary to read
  WSDL documents and create classes and methods on the
  fly.
• Sample Java server code based on XFire samples can be
  found here:http://agylen.com/2006/05/06/ruby-for-java-
  programmers-part-vi/.




                                     Ugo Cei: “Ruby for Java Programmers”
services.xml
• Maps service names to service classes:

<beans xmlns=quot;http://xfire.codehaus.org/config/1.0quot;>
 <service>
  <name>BookService</name>
  <namespace>http://sourcesense.com/BookService</namespace>
  <serviceClass>com.sourcesense.xfire.demo.BookService</serviceClass>
 </service>
</beans>




                                             Ugo Cei: “Ruby for Java Programmers”
SOAP Ruby Client
 require 'soap/wsdlDriver'
 WSDL_URL = 'http://localhost:8080/services/BookService?wsdl'
 driver = SOAP::WSDLDriverFactory.new(WSDL_URL).create_rpc_driver
 books = driver.getBooks(nil)
 p books.out.book[0].title
 book = driver.findBook(:isbn => '222')
 p book.out.title


• The BookService#getBooks method in Java takes no
  arguments, but if you try to call driver.getBooks without
  arguments, Ruby complains about a missing argument.
• XFire add this extra ‘out’ element to its generated schema.


                                              Ugo Cei: “Ruby for Java Programmers”
Thank You!

  Slides will be available at
       http://agylen.com/
              and at
http://www.sourcesense.com/


                     Ugo Cei: “Ruby for Java Programmers”

Weitere ähnliche Inhalte

Was ist angesagt?

Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developergicappa
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development toolsSimon Kim
 
Артем Яворский "Compile like it's 2017"
Артем Яворский "Compile like it's 2017"Артем Яворский "Compile like it's 2017"
Артем Яворский "Compile like it's 2017"Fwdays
 
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Alberto Perdomo
 
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsSteven Evatt
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 
Distributed Ruby and Rails
Distributed Ruby and RailsDistributed Ruby and Rails
Distributed Ruby and RailsWen-Tien Chang
 
Security Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSecurity Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSource Conference
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with PerlDave Cross
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play appsYevgeniy Brikman
 
Rails Girls: Programming, Web Applications and Ruby on Rails
Rails Girls: Programming, Web Applications and Ruby on RailsRails Girls: Programming, Web Applications and Ruby on Rails
Rails Girls: Programming, Web Applications and Ruby on RailsDonSchado
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with RackDonSchado
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications Juliana Lucena
 
Lightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClientLightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClientAdam Wiggins
 

Was ist angesagt? (20)

Ruby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developerRuby on Rails survival guide of an aged Java developer
Ruby on Rails survival guide of an aged Java developer
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
Артем Яворский "Compile like it's 2017"
Артем Яворский "Compile like it's 2017"Артем Яворский "Compile like it's 2017"
Артем Яворский "Compile like it's 2017"
 
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
 
Migrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain PointsMigrating PriceChirp to Rails 3.0: The Pain Points
Migrating PriceChirp to Rails 3.0: The Pain Points
 
Java presentation
Java presentationJava presentation
Java presentation
 
Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Distributed Ruby and Rails
Distributed Ruby and RailsDistributed Ruby and Rails
Distributed Ruby and Rails
 
Security Goodness with Ruby on Rails
Security Goodness with Ruby on RailsSecurity Goodness with Ruby on Rails
Security Goodness with Ruby on Rails
 
Open Social Summit Korea
Open Social Summit KoreaOpen Social Summit Korea
Open Social Summit Korea
 
Modern Web Development with Perl
Modern Web Development with PerlModern Web Development with Perl
Modern Web Development with Perl
 
Composable and streamable Play apps
Composable and streamable Play appsComposable and streamable Play apps
Composable and streamable Play apps
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Rails Girls: Programming, Web Applications and Ruby on Rails
Rails Girls: Programming, Web Applications and Ruby on RailsRails Girls: Programming, Web Applications and Ruby on Rails
Rails Girls: Programming, Web Applications and Ruby on Rails
 
Ruby MVC from scratch with Rack
Ruby MVC from scratch with RackRuby MVC from scratch with Rack
Ruby MVC from scratch with Rack
 
遇見 Ruby on Rails
遇見 Ruby on Rails遇見 Ruby on Rails
遇見 Ruby on Rails
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
 
Lightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClientLightweight Webservices with Sinatra and RestClient
Lightweight Webservices with Sinatra and RestClient
 

Andere mochten auch (6)

State Of Rails 05
State Of Rails 05State Of Rails 05
State Of Rails 05
 
Workin On The Rails Road
Workin On The Rails RoadWorkin On The Rails Road
Workin On The Rails Road
 
Extractingrails
ExtractingrailsExtractingrails
Extractingrails
 
Fisl6
Fisl6Fisl6
Fisl6
 
Secretsofrubyonrails
SecretsofrubyonrailsSecretsofrubyonrails
Secretsofrubyonrails
 
Pursuitofbeauty
PursuitofbeautyPursuitofbeauty
Pursuitofbeauty
 

Ähnlich wie Ugo Cei Presentation

JRuby - Enterprise 2.0
JRuby - Enterprise 2.0JRuby - Enterprise 2.0
JRuby - Enterprise 2.0Jan Sifra
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaKeith Bennett
 
JRoR Deploying Rails on JRuby
JRoR Deploying Rails on JRubyJRoR Deploying Rails on JRuby
JRoR Deploying Rails on JRubyelliando dias
 
J Ruby Power On The Jvm
J Ruby Power On The JvmJ Ruby Power On The Jvm
J Ruby Power On The JvmQConLondon2008
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with RubyAnis Ahmad
 
Ola Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The JvmOla Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The Jvmdeimos
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby.toster
 
JRuby - Java version of Ruby
JRuby - Java version of RubyJRuby - Java version of Ruby
JRuby - Java version of RubyUday Bhaskar
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMRaimonds Simanovskis
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBrian Sam-Bodden
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09Michael Neale
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2rubyMarc Chung
 
JRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudJRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudHiro Asari
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Enginecatherinewall
 
Monkeybars in the Manor
Monkeybars in the ManorMonkeybars in the Manor
Monkeybars in the Manormartinbtt
 
Server-Side JavaScript with jQuery and AOLserver
Server-Side JavaScript with jQuery and AOLserverServer-Side JavaScript with jQuery and AOLserver
Server-Side JavaScript with jQuery and AOLserverDossy Shiobara
 
RJB - another choice for Ruby and Java interoperability
RJB - another choice for Ruby and Java interoperabilityRJB - another choice for Ruby and Java interoperability
RJB - another choice for Ruby and Java interoperabilityAkio Tajima
 

Ähnlich wie Ugo Cei Presentation (20)

JRuby - Enterprise 2.0
JRuby - Enterprise 2.0JRuby - Enterprise 2.0
JRuby - Enterprise 2.0
 
Jruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-javaJruby synergy-of-ruby-and-java
Jruby synergy-of-ruby-and-java
 
JRuby Basics
JRuby BasicsJRuby Basics
JRuby Basics
 
JRoR Deploying Rails on JRuby
JRoR Deploying Rails on JRubyJRoR Deploying Rails on JRuby
JRoR Deploying Rails on JRuby
 
J Ruby Power On The Jvm
J Ruby Power On The JvmJ Ruby Power On The Jvm
J Ruby Power On The Jvm
 
Developing cross platform desktop application with Ruby
Developing cross platform desktop application with RubyDeveloping cross platform desktop application with Ruby
Developing cross platform desktop application with Ruby
 
Ola Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The JvmOla Bini J Ruby Power On The Jvm
Ola Bini J Ruby Power On The Jvm
 
The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
Практики применения JRuby
Практики применения JRubyПрактики применения JRuby
Практики применения JRuby
 
JRuby - Java version of Ruby
JRuby - Java version of RubyJRuby - Java version of Ruby
JRuby - Java version of Ruby
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVM
 
Bitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRubyBitter Java, Sweeten with JRuby
Bitter Java, Sweeten with JRuby
 
Jaoo Michael Neale 09
Jaoo Michael Neale 09Jaoo Michael Neale 09
Jaoo Michael Neale 09
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
JRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the CloudJRuby, Ruby, Rails and You on the Cloud
JRuby, Ruby, Rails and You on the Cloud
 
hacking with node.JS
hacking with node.JShacking with node.JS
hacking with node.JS
 
Cannibalising The Google App Engine
Cannibalising The  Google  App  EngineCannibalising The  Google  App  Engine
Cannibalising The Google App Engine
 
Monkeybars in the Manor
Monkeybars in the ManorMonkeybars in the Manor
Monkeybars in the Manor
 
Server-Side JavaScript with jQuery and AOLserver
Server-Side JavaScript with jQuery and AOLserverServer-Side JavaScript with jQuery and AOLserver
Server-Side JavaScript with jQuery and AOLserver
 
RJB - another choice for Ruby and Java interoperability
RJB - another choice for Ruby and Java interoperabilityRJB - another choice for Ruby and Java interoperability
RJB - another choice for Ruby and Java interoperability
 

Mehr von RubyOnRails_dude

Mehr von RubyOnRails_dude (8)

Slides
SlidesSlides
Slides
 
Rails Conf Talk Slides
Rails Conf Talk SlidesRails Conf Talk Slides
Rails Conf Talk Slides
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
Marcel Molina Jr. Presentation
Marcel Molina Jr. PresentationMarcel Molina Jr. Presentation
Marcel Molina Jr. Presentation
 
Rails4 Days
Rails4 DaysRails4 Days
Rails4 Days
 
Programminghappiness
ProgramminghappinessProgramminghappiness
Programminghappiness
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 
Worldofresources
WorldofresourcesWorldofresources
Worldofresources
 

Kürzlich hochgeladen

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 

Kürzlich hochgeladen (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 

Ugo Cei Presentation

  • 1. Ruby for Java programmers Ugo Cei Sourcesense u.cei@sourcesense.com
  • 2. Who should attend this talk • Java programmers wishing to know how to include Ruby code in Java programs or vice-versa. • Ruby programmers wishing for the same. Who should NOT attend this talk • Java programmers wishing to learn more about the Ruby programming language. • This is not a talk about the differences between Java and Ruby. Ugo Cei: “Ruby for Java Programmers”
  • 3. Agenda • Why? • How? • Bridges • JRuby • XML-RPC • SOAP • Demos Ugo Cei: “Ruby for Java Programmers”
  • 4. What’s in it for me? Ugo Cei: “Ruby for Java Programmers”
  • 5. Shameless Plug: The Open Source Zone http://oszone.org Ugo Cei: “Ruby for Java Programmers”
  • 6. Shameless Plug: The Open Source Zone http://oszone.org Ugo Cei: “Ruby for Java Programmers”
  • 7. Shameless Plug: Evil or Not? http://evilornot.info Ugo Cei: “Ruby for Java Programmers”
  • 8. Shameless Plug: Evil or Not? if /<title>(.+)</title>/ ... Search? http://evilornot.info Ugo Cei: “Ruby for Java Programmers”
  • 9.
  • 10. “The era of islands is over for most development scenarios. You don't have to make one definitive choice. Instead, you get to hog all the productivity you can for the common cases, then outsource the bottlenecks to existing packages in faster languages or build your own tiny extension when it's needed.” David Heinemeier Hansson, Sep 13, 2006 Ugo Cei: “Ruby for Java Programmers”
  • 11. How? Ugo Cei: “Ruby for Java Programmers”
  • 12. RubyJavaBridge • http://arton.no-ip.info/collabo/backyard/?RubyJavaBridge • Follow the instructions in readme.txt and on the website and it should work (even on Intel Macs). • Encapsulate you Java code in high-level methods and classes to hide 3rd party libraries and Java idiosyncrasies from Ruby as much as possible. Ugo Cei: “Ruby for Java Programmers”
  • 13. Sample Java Code • Uses ROME (https://rome.dev.java.net). public class Fetcher { public static SyndFeed fetch(String url) throws Exception { URL feedUrl = new URL(url); FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance(); FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache); SyndFeed feed = fetcher.retrieveFeed(feedUrl); return feed; } } Ugo Cei: “Ruby for Java Programmers”
  • 14. Client Ruby Code require 'rjb' Rjb::load('.:rome-0.7.jar:rome-fetcher-0.7.jar:jdom.jar:jdom.jar', []) fetcher = Rjb::import('Fetcher') feed = fetcher.fetch(ARGV[0]) print feed.getTitle, “n” entries = feed.getEntries.iterator while entries.hasNext do entry = entries.next print quot;#{entry.getPublishedDate.toString} #{entry.getTitle}nquot; end • No mapping from Java iterators to Ruby loops. • No date type conversions. • No support for JavaBean properties. Ugo Cei: “Ruby for Java Programmers”
  • 15. YAJB • http://www.cmt.phys.kyushu-u.ac.jp/~M.Sakurai/cgi-bin/fw/ wiki.cgi?page=YAJB • Same caveats and limitations as for RJB. Ugo Cei: “Ruby for Java Programmers”
  • 16. Client Ruby Code require 'yajb/jbridge' include JavaBridge JBRIDGE_OPTIONS = { :classpath => '.:rome-0.7.jar:rome-fetcher-0.7.jar:jdom.jar:jdom.jar' } jimport quot;Fetcherquot; feed = :Fetcher.jclass.fetch(ARGV[0]) print feed.getTitle, quot;nquot; entries = feed.getEntries.iterator while entries.hasNext do entry = entries.next print quot;#{entry.getPublishedDate.toString} #{entry.getTitle}nquot; end Ugo Cei: “Ruby for Java Programmers”
  • 17. Making a Simple Java Class require 'yajb/jbridge' require 'yajb/jlambda' include JavaBridge c = JClassBuilder.new(quot;MyClassquot;) c.add_field(quot;private int num;quot;) c.add_constructor(quot;public AAA(int a) {num = a;}quot;) c.add_method(quot;public int square() { return num * num;}quot;) puts quot;Simple class: #{c.new_instance(5).square}quot; • Uses javassist: http://www.csg.is.titech.ac.jp/~chiba/ javassist/index.html Ugo Cei: “Ruby for Java Programmers”
  • 18. Implementing an Interface jimport quot;java.util.*quot; c = JClassBuilder.new(quot;NumCompquot;) c.add_interface(quot;java.util.Comparatorquot;) # must be full qualified class name c.add_method(<<'JAVA') public int compare(Object o1, Object o2) do int i1 = ((Number)o1).intValue(); int i2 = ((Number)o2).intValue(); return i2-i1; end JAVA sample = [9,1,8,2,7,3,6,4,5,0,10] list = :ArrayList.jnew sample.each {|i| list.add( i ) } :Collections.jclass.sort(list, c.new_instance) p quot;Sort:quot;,list.toArray Ugo Cei: “Ruby for Java Programmers”
  • 19. Using SWIG • http://www.swig.org • Jakarta POI, nifty library for manipulating Microsoft OLE 2 Compound Document formats (Office files) uses SWIG to provide Ruby bindings. • POI compiled using gcj and Ruby bindings generated using SWIG. • http://jakarta.apache.org/poi/poi-ruby.html Ugo Cei: “Ruby for Java Programmers”
  • 20. JRuby • http://jruby.sourceforge.net/ • http://jruby.codehaus.org/ • JRuby is not a bridge between Java and Ruby but a full- featured Ruby interpreter written in 100% Java. • Gives Ruby code instant access to all Java libraries. • Cannot load Ruby extensions written in C. • “Almost” Mostly able to run RubyGems and Rails. • Quick development pace. • Still slow compared to C Ruby, but quoting Charles O. Nutter: “I think it's now very reasonable to say we could beat C Ruby performance by the end of the year.” Ugo Cei: “Ruby for Java Programmers”
  • 21. JRuby Client Code require 'java' include_class 'Fetcher' feed = Fetcher.fetch(ARGV[0]) feed.entries.each do | entry | p quot;#{entry.publishedDate} #{entry.title}quot; end • Can use “each” on Java collections. • Date type conversion. • Full support for JavaBean properties. Ugo Cei: “Ruby for Java Programmers”
  • 22. Calling Ruby Methods • demo1.rb class Demo1 def foo print 'bar' end end • Demo1.java IRuby runtime = Ruby.getDefaultInstance(); runtime.loadFile(new File(quot;ruby/demo1.rbquot;), false); RubyClass rb = runtime.getClass(quot;Demo1quot;); IRubyObject obj = rb.newInstance(new RubyObject[0]); obj.callMethod(quot;fooquot;); Ugo Cei: “Ruby for Java Programmers”
  • 23. Using the Bean Scripting Framework • The Bean Scripting Framework, when used with JRuby, will allow you more conveniently to pass your own Java objects to your JRuby script. You can then use these objects in JRuby, and changes will affect your Java program directly. BSFManager.registerScriptingEngine(quot;rubyquot;, quot;org.jruby.javasupport.bsf.JRubyEnginequot;, new String[] { quot;rbquot; }); BSFManager manager = new BSFManager(); JLabel mylabel = new JLabel(); manager.declareBean(quot;labelquot;, mylabel, JLabel.class); manager.exec(quot;rubyquot;, quot;(java)quot;, 1, 1, quot;$label.setText(quot;This is a test.quot;)quot;); Ugo Cei: “Ruby for Java Programmers”
  • 24. Name Clashes import_class ‘java.lang.String’ import_class ‘java.net.URI’ • This won’t work as it conflicts with Ruby’s String and URI classes. • Solution: use a module. module Java import_class ‘java.lang.String’ import_class ‘java.net.URI’ end ... uri = Java::URI.new(‘http://example.com/’) • Or remap names: include_class(quot;java.lang.Exceptionquot;) {|p,n| quot;Jquot; + n } Ugo Cei: “Ruby for Java Programmers”
  • 25. Running Ruby on Rails Ugo Cei: “Ruby for Java Programmers”
  • 26. Running Camping • http://jruby.codehaus.org/The+JRuby+Tutorial+Part+2+- +Going+Camping Ugo Cei: “Ruby for Java Programmers”
  • 27. Using the JDBC AR Adapter jruby $JRUBY_HOME/bin/gem install ActiveRecord-JDBC --no-ri --no-rdoc • As of 0.2.0 works for: • MySQL • PostgreSQL • Oracle • HSQLDB • Microsoft SQL Server • DB2 • Apache Derby • FireBird Ugo Cei: “Ruby for Java Programmers”
  • 28. Using the JDBC AR Adapter adapter: jdbc driver: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/dbname username: admin password: secret Ugo Cei: “Ruby for Java Programmers”
  • 29. XML-RPC • Pro: Established technology. • Pro: No need to use bridge code or special interpreters. • Con: Separate processes => must take network latency and failures into account. • Con: Overhead of HTTP communication, XML parsing, marshalling... • Need to convert types to something that XML-RPC is able to understand, i.e.strings, numbers, dates, Vectors, Hashtables and little else. Ugo Cei: “Ruby for Java Programmers”
  • 30. XML-RPC Java Server • Uses Apache XML-RPC. public class RPCFetcher { public static void main(String args[]) throws Exception { WebServer server = new WebServer(8080); server.addHandler(quot;$defaultquot;, new RPCFetcher()); server.start(); } // Continued... Ugo Cei: “Ruby for Java Programmers”
  • 31. XML-RPC Java Server public Vector fetch(String url) throws Exception { URL feedUrl = new URL(url); FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance(); FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache); SyndFeed feed = fetcher.retrieveFeed(feedUrl); Vector items = new Vector(); for (Iterator it = feed.getEntries().iterator() ; it.hasNext() ; ) { SyndEntry entry = (SyndEntry) it.next(); Hashtable map = new Hashtable(); map.put(quot;linkquot;, entry.getLink()); map.put(quot;titlequot;, entry.getTitle()); map.put(quot;publishedDatequot;, entry.getPublishedDate()); items.add(map); } return items; } Ugo Cei: “Ruby for Java Programmers”
  • 32. XML-RPC Ruby Client require 'xmlrpc/client' server = XMLRPC::Client.new 'localhost', '/', 8080 entries = server.call('fetch', 'http://agylen.com/feed') entries.each do | entry | p quot;#{entry['publishedDate'].to_time} #{entry['title']}quot; end Ugo Cei: “Ruby for Java Programmers”
  • 33. SOAP • Complex and heavyweight, but most of the complexity is hidden by tools. • WSDL service description can be automatically generated from server code. • Ruby’s SOAP library provides what is necessary to read WSDL documents and create classes and methods on the fly. • Sample Java server code based on XFire samples can be found here:http://agylen.com/2006/05/06/ruby-for-java- programmers-part-vi/. Ugo Cei: “Ruby for Java Programmers”
  • 34. services.xml • Maps service names to service classes: <beans xmlns=quot;http://xfire.codehaus.org/config/1.0quot;> <service> <name>BookService</name> <namespace>http://sourcesense.com/BookService</namespace> <serviceClass>com.sourcesense.xfire.demo.BookService</serviceClass> </service> </beans> Ugo Cei: “Ruby for Java Programmers”
  • 35. SOAP Ruby Client require 'soap/wsdlDriver' WSDL_URL = 'http://localhost:8080/services/BookService?wsdl' driver = SOAP::WSDLDriverFactory.new(WSDL_URL).create_rpc_driver books = driver.getBooks(nil) p books.out.book[0].title book = driver.findBook(:isbn => '222') p book.out.title • The BookService#getBooks method in Java takes no arguments, but if you try to call driver.getBooks without arguments, Ruby complains about a missing argument. • XFire add this extra ‘out’ element to its generated schema. Ugo Cei: “Ruby for Java Programmers”
  • 36. Thank You! Slides will be available at http://agylen.com/ and at http://www.sourcesense.com/ Ugo Cei: “Ruby for Java Programmers”