Course JRuby Programs
Here are all the programs that we would be discussing while learning JRuby at rubylearning.org.
#jruby01a.rb
JS = Java::java.lang.System
os = JS.get_property 'os.name'
home = JS.get_property 'java.home'
mem = Java::java.lang.Runtime.get_runtime.free_memory
puts "Running on #{os}"
puts "Java home is #{home}"
puts "#{mem} bytes available in JVM"
# jruby01.rb
require 'java'
#java_import 'java.util.Date'
java_import('java.util.Date') { |pkg,name| 'JDate' }
java_import 'java.text.DateFormat'
date = JDate.new
date_format = DateFormat.get_date_instance
date_us = date_format .format date
puts date_us
# jruby02.rb
require 'java'
java_import 'java.lang.String' do |package,name|
"J#{name}"
end
ResourceBundle = java.util.ResourceBundle
Locale = java.util.Locale
lang = JString.new 'de'
country = JString.new 'DE'
cLocale = Locale.new lang, country
msg = ResourceBundle.get_bundle 'MessagesBundle', cLocale
puts msg.get_string 'greetings'
puts msg.get_string 'welcome'
# jruby03.rb
require 'java'
JFrame = javax.swing.JFrame
JLabel = javax.swing.JLabel
frame = JFrame.new
jlabel = JLabel.new 'Hello World'
frame.add jlabel
frame.set_default_close_operation JFrame::EXIT_ON_CLOSE
frame.pack
frame.set_size 200, 200
frame.set_visible true
# jruby04.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter=> "jdbcmysql",
:host => "localhost",
:database=> "students",
:username => "root",
:password => ""
)
class Rubyist < ActiveRecord::Base
end
Rubyist.create(:name => 'Mitali Talim', :city => "Nashville, Tenessee")
Rubyist.create(:name => 'Sunil Kelkar', :city => "Pune, India")
Rubyist.create(:name => 'Adam Smith', :city => "San Fransisco, USA")
participant = Rubyist.find(:first)
puts %{#{participant.name} stays in #{participant.city}}
Rubyist.find(:first).destroy
// JRubyJSR223.java
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptContext;
public class JRubyJSR223
{
public static void main(String[] args) throws Exception
{
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine rubyEngine = m.getEngineByName("jruby");
rubyEngine.getContext().setAttribute("label", new Integer(4), ScriptContext.ENGINE_SCOPE);
rubyEngine.eval("puts 2 + $label");
}
}
/*
To execute the program -
C:\>java -cp E:\jruby-1.1.3\lib\jruby.jar;E:\jruby-1.1.3\lib\jruby-engine.jar;.; JRubyJSR223
*/
// JRubyJSR223Rx2.java
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.ScriptContext;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class JRubyJSR223Ex2
{
public static void main(String[] args) throws ScriptException, FileNotFoundException
{
//list all available scripting engines
listScriptingEngines();
//get jruby engine
ScriptEngine jruby = new ScriptEngineManager().getEngineByName("jruby");
//process a ruby file
jruby.eval(new BufferedReader(new FileReader("myfact.rb")));
//call a method defined in the ruby source
jruby.put("number", 6);
long fact = (Long) jruby.eval("fact($number)");
System.out.println("fact: " + fact);
jruby.eval("$myglobalvar = fact($number)");
long myglob = (Long) jruby.getBindings(ScriptContext.ENGINE_SCOPE).get("myglobalvar");
System.out.println("myglob: " + myglob);
}
public static void listScriptingEngines()
{
ScriptEngineManager mgr = new ScriptEngineManager();
for (ScriptEngineFactory factory : mgr.getEngineFactories())
{
System.out.println("ScriptEngineFactory Info");
System.out.printf("\tScript Engine: %s (%s)\n", factory.getEngineName(), factory.getEngineVersion());
System.out.printf("\tLanguage: %s (%s)\n", factory.getLanguageName(), factory.getLanguageVersion());
for (String name : factory.getNames())
{
System.out.printf("\tEngine Alias: %s\n", name);
}
}
}
}
/*
To execute the program -
C:\>java -cp E:\jruby-1.1.3\lib\jruby.jar;E:\jruby-1.1.3\lib\jruby-engine.jar;.; JRubyJSR223Ex2
*/
# myfact.rb
# computes the factorial of a given number
def fact(n)
if n==0
return 1
else
return n*fact(n-1)
end
end
# Assignment 1
# frontend.rb
require 'java'
require 'swing'
require 'awt'
class FrontEnd < Swing::JFrame
def initialize(title)
super(title)
initComponents
end
private
def initComponents
# Create all the UI objects
flow_layout = Awt::FlowLayout.new(Awt::FlowLayout::LEFT)
grid_layout = Awt::GridLayout.new(3,2)
@l_panel = Swing::JPanel.new
@label = Swing::JLabel.new 'A Simple Application'
@main_panel = Swing::JPanel.new
@main_panel.set_layout(grid_layout)
@lid = Swing::JLabel.new 'LoginId'
@lpass = Swing::JLabel.new 'Password'
@lname = Swing::JLabel.new 'Message'
@tid = Swing::JTextField.new(10)
@tpass = Swing::JTextField.new(10)
@tname = Swing::JTextField.new(20)
@tname.set_editable(false)
@p1 = Swing::JPanel.new
@p1.set_layout(flow_layout)
@p2 =Swing::JPanel.new
@p2.set_layout(flow_layout)
@p3 = Swing::JPanel.new
@p3.set_layout(flow_layout)
@p4 = Swing::JPanel.new
@p4.set_layout(flow_layout)
@p5 = Swing::JPanel.new
@p5.set_layout(flow_layout)
@p6 = Swing::JPanel.new
@p6.set_layout(flow_layout)
@p1.add(@lid)
@p2.add(@tid)
@p3.add(@lpass)
@p4.add(@tpass)
@p5.add(@lname)
@p6.add(@tname)
@main_panel.add(@p1)
@main_panel.add(@p2)
@main_panel.add(@p3)
@main_panel.add(@p4)
@main_panel.add(@p5)
@main_panel.add(@p6)
@l_panel.add(@label)
@b = Swing::JButton.new("Submit")
@br = Swing::JButton.new("Refresh")
@b_panel = Swing::JPanel.new
@b_panel.add(@b)
@b_panel.add(@br)
# Add the UI objects to the frame
self.add(@l_panel, Awt::BorderLayout::NORTH)
self.add(@main_panel, Awt::BorderLayout::CENTER)
self.add(@b_panel, Awt::BorderLayout::SOUTH)
# Show frame
self.set_default_close_operation(Swing::WindowConstants::EXIT_ON_CLOSE)
self.set_resizable(false)
self.pack
self.set_visible(true)
end
end
# Usage
f = FrontEnd.new('Assignment 1')
# awt.rb
# Bundle Java AWT and AWT event packages for ease of reference
require 'java'
module Awt
include_package 'java.awt'
include_package 'java.awt.event'
end
# swing.rb
# Bundle Swing API and Swing Layout Extension (require swing-layout-1.0.2.jar)
include Java
module Swing
include_package 'javax.swing'
include_package 'javax.swing.event'
end
# Assignment 2
# Modified frontend.rb
# programs used: frontend.rb, backend.rb, awt.rb, swing.rb, clickaction.rb
require 'java'
require 'swing'
require 'awt'
require 'clickaction'
class FrontEnd < Swing::JFrame
def initialize(title)
super(title)
initComponents
end
def get_user_input
return {'id' => @tid.get_text, 'pass' => @tpass.get_text}
end
def show_result result
@tname.set_text(result)
end
def refresh_screen
@tid.set_text("")
@tpass.set_text("")
@tname.set_text("")
@tid.request_focus
end
private
def initComponents
# Create all the UI objects
flow_layout = Awt::FlowLayout.new(Awt::FlowLayout::LEFT)
grid_layout = Awt::GridLayout.new(3,2)
@l_panel = Swing::JPanel.new
@label = Swing::JLabel.new 'A Simple Application'
@main_panel = Swing::JPanel.new
@main_panel.set_layout(grid_layout)
@lid = Swing::JLabel.new 'LoginId'
@lpass = Swing::JLabel.new 'Password'
@lname = Swing::JLabel.new 'Message'
@tid = Swing::JTextField.new(10)
@tpass = Swing::JTextField.new(10)
@tname = Swing::JTextField.new(20)
@tname.set_editable(false)
@p1 = Swing::JPanel.new
@p1.set_layout(flow_layout)
@p2 =Swing::JPanel.new
@p2.set_layout(flow_layout)
@p3 = Swing::JPanel.new
@p3.set_layout(flow_layout)
@p4 = Swing::JPanel.new
@p4.set_layout(flow_layout)
@p5 = Swing::JPanel.new
@p5.set_layout(flow_layout)
@p6 = Swing::JPanel.new
@p6.set_layout(flow_layout)
@p1.add(@lid)
@p2.add(@tid)
@p3.add(@lpass)
@p4.add(@tpass)
@p5.add(@lname)
@p6.add(@tname)
@main_panel.add(@p1)
@main_panel.add(@p2)
@main_panel.add(@p3)
@main_panel.add(@p4)
@main_panel.add(@p5)
@main_panel.add(@p6)
@l_panel.add(@label)
@b = Swing::JButton.new("Submit")
@br = Swing::JButton.new("Refresh")
@b_panel = Swing::JPanel.new
@b_panel.add(@b)
@b_panel.add(@br)
@b.add_action_listener ClickAction.new(self)
@br.add_action_listener ClickAction.new(self)
# Add the UI objects to the frame
self.add(@l_panel, Awt::BorderLayout::NORTH)
self.add(@main_panel, Awt::BorderLayout::CENTER)
self.add(@b_panel, Awt::BorderLayout::SOUTH)
# Show frame
self.set_default_close_operation(Swing::WindowConstants::EXIT_ON_CLOSE)
self.set_resizable(false)
self.pack
self.set_visible(true)
end
end
# Usage
f = FrontEnd.new('Assignment 2')
# clickaction.rb
require 'java'
require 'swing'
require 'awt'
require 'backend'
class ClickAction
include Awt::ActionListener
private
attr_accessor :view
def initialize(view)
@view = view
# Create the Login object
@backend = Backend.new
end
public
def actionPerformed(e)
user_input = @view.get_user_input
id = user_input['id']
pass = user_input['pass']
if ("Submit".eql?(e.get_action_command))
result = @backend.authenticate_safely_simply(id, pass)
@view.show_result result
else
@view.refresh_screen
end
end
end
# backend.rb
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter=> "jdbcmysql",
:host => "localhost",
:database=> "assignments",
:username => "root",
:password => ""
)
class Backend < ActiveRecord::Base
def insert_records
Backend.create(:loginid => '01', :password => 'satish', :name => "Satish Talim")
Backend.create(:loginid => '02', :password => 'sunil', :name => "Sunil Kelkar")
Backend.create(:loginid => '03', :password => 'fabio', :name => "Fabio Akita")
end
def find_first
user = Backend.find(:first)
puts %{#{user.name} is a valid user of the system}
end
# authenticate_safely_simply will sanitize the user_name and password before inserting them in the query,
# which will ensure that an attacker can't escape the query and fake the login (or worse).
def authenticate_safely_simply(loginid, password)
#user = Backend.find(:first, :conditions => { :loginid => loginid, :password => password })
# we could also use Dynamic Finders
# begin
# See note below
user = Backend.find_by_loginid_and_password(loginid, password)
if user.nil?
# no such user, let them retry
return "Sorry no such user..."
else
# log them in
return "Welcome " + user.name
end
=begin
#puts %{#{user.name} is a valid user of the system}
return "Welcome " + user.name
rescue #ActiveRecord::RecordNotFound
return "Sorry no such user..."
=end
end
end
=begin
b = Backend.new
#b.insert_records
b.find_first
b.authenticate_safely_simply('02','sunil')
=end
=begin
create database assignments;
grant all on assignments.* to 'root'@'localhost';
use assignments;
drop table if exists backends;
create table backends (
id int not null auto_increment,
loginid varchar(10) not null,
password varchar(20) not null,
name text not null,
primary key (id)
);
=end
=begin
The method Backend.find_by_loginid_and_password(loginid, password)
This is a Dynamic finder and also a syntactic sugar in ActiveRecord.
Explanatuon - http://weblog.jamisbuck.org/2006/12/1/under-the-hood-activerecord-base-find-part-3
=end