#!/usr/bin/env ruby $:.unshift File.expand_path '../lib', File.dirname(__FILE__) require 'rubygems' require 'sinatra/rocketio/linda/client' require 'args_parser' $stdout.sync = true args = ArgsParser.parse ARGV do arg :tuple, 'tuple(s)' arg :base, 'linda base URL' arg :space, 'linda space name' arg :timeout, 'wait (sec)', :default => 10 arg :verbose, 'verbose mode', :alias => :v arg :help, 'show help', :alias => :h validate :base, "invalid linda URL" do |v| v =~ /^https?:\/\/.+/ end filter :tuple do |v| JSON.parse v end end class Console def self.enable=(bool) @@enable = bool end def self.enable? @@enable end def self.log(str) STDOUT.puts "* #{str}" if enable? end def self.error(str) STDERR.puts "! #{str}" if enable? end end Console.enable = args.has_option? :verbose if args.has_option? :help or !args.has_param?(:base, :space) or !["read","write","take","watch"].include?(args.first) bin = $0.split("/").last STDERR.puts "RocketIO::Linda v#{Sinatra::RocketIO::Linda::VERSION}" STDERR.puts " - https://github.com/shokai/sinatra-rocketio-linda" STDERR.puts STDERR.puts args.help STDERR.puts STDERR.puts "e.g." STDERR.puts %Q{write #{bin} write -tuple '["say","hello"]' -base http://example.com -space test} STDERR.puts %Q{ echo '["say","hello"]\\n["say","world"]' | #{bin} write -base http://example.com -space test} STDERR.puts %Q{read #{bin} read -tuple '["say"]' -base http://example.com -space test} STDERR.puts %Q{take #{bin} take -tuple '["say"]' -base http://example.com -space test} STDERR.puts %Q{watch #{bin} watch -tuple '["say"]' -base http://example.com -space test} exit 1 end io = Sinatra::RocketIO::Client.new args[:base] linda = Sinatra::RocketIO::Linda::Client.new io ts = linda.tuplespace[ args[:space] ] linda.io.on :connect do Console.log "connect #{io.session} (#{io.type})" case args.first when "write" if args.has_param? :tuple Console.log "write #{args[:tuple].to_json}" ts.write args[:tuple] exit else while line = STDIN.gets do begin tuple = JSON.parse line.strip Console.log "write #{tuple.to_json}" puts tuple.to_json ts.write tuple rescue => e Console.error e end end exit end when "read" Console.log "read #{args[:tuple].to_json}" ts.read args[:tuple] do |tuple| puts tuple.to_json exit end when "take" Console.log "take #{args[:tuple].to_json}" ts.take args[:tuple] do |tuple| puts tuple.to_json exit end when "watch" Console.log "watch #{args[:tuple].to_json}" ts.watch args[:tuple] do |tuple| puts tuple.to_json end else exit 1 end end linda.io.on :disconnect do Console.log "disconnect #{io.session} (#{io.type})" end Console.log "waiting #{args[:base]}" io.connect if [Fixnum, Float].include? args[:timeout].class and args[:timeout] > 0 and args.first != "watch" and !(args.first == "write" and !args.has_param?(:tuple)) sleep args[:timeout] else linda.wait end Console.log "timeout (#{args[:timeout]}sec)"