repo
string | commit
string | message
string | diff
string |
---|---|---|---|
binaryage/totalfinder-i18n
|
e5656a258a4cf4f8fec297f532488b1d91244c48
|
ah, add missing end-line dot
|
diff --git a/installer/en.lproj/welcome.rtf b/installer/en.lproj/welcome.rtf
index 0fac05b..ca0a1d7 100644
--- a/installer/en.lproj/welcome.rtf
+++ b/installer/en.lproj/welcome.rtf
@@ -1,34 +1,34 @@
{\rtf1\ansi\ansicpg1252\cocoartf1561\cocoasubrtf600
\cocoascreenfonts1{\fonttbl\f0\fnil\fcharset0 HelveticaNeue;}
{\colortbl;\red255\green255\blue255;\red255\green0\blue0;\red158\green0\blue6;}
{\*\expandedcolortbl;;\csgenericrgb\c100000\c0\c0;\csgenericrgb\c61961\c0\c2353;}
\paperw11900\paperh16840\margl1440\margr1440\vieww16580\viewh16600\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\f0\fs24 \cf0 This installer will install {\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com"}}{\fldrslt
\b TotalFinder}} on your computer.\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
{\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/about"}}{\fldrslt \cf0 https://totalfinder.binaryage.com/about}}\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\cf2 \
Please finish all background jobs like copying or moving files.\cf3 \
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\cf0 Finder will be restarted during the installation.\
\
Prior to buying you have 14 days to evaluate the product. \
For more info on licensing please visit:\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
{\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/licensing"}}{\fldrslt \cf0 https://totalfinder.binaryage.com/licensing}}\
\
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\b\fs28 \cf0 A note about System Integrity Protection (SIP)
\b0\fs24 \
\
-SIP is a security subsystem introduced in macOS 10.11 (El Capitan)\
+SIP is a security subsystem introduced in macOS 10.11 (El Capitan).\
Unfortunately it prevents TotalFinder from altering Finder.\
\
The only known workaround is to disable SIP.\
\
Please read more about TotalFinder and SIP:\
{\field{\*\fldinst{HYPERLINK "https://totalfinder.binaryage.com/system-integrity-protection"}}{\fldrslt https://totalfinder.binaryage.com/sip-mojave}}}
\ No newline at end of file
|
bernerdschaefer/akephalos
|
80103301ebe1609b90de04a8e4f6092def818585
|
Use new registration name in bin/akephalos
|
diff --git a/lib/akephalos/console.rb b/lib/akephalos/console.rb
index 7beb575..dbcfef4 100644
--- a/lib/akephalos/console.rb
+++ b/lib/akephalos/console.rb
@@ -1,32 +1,32 @@
# Begin a new Capybara session, by default connecting to localhost on port
# 3000.
def session
Capybara.app_host ||= "http://localhost:3000"
- @session ||= Capybara::Session.new(:Akephalos)
+ @session ||= Capybara::Session.new(:akephalos)
end
alias page session
module Akephalos
# Simple class for starting an IRB session.
class Console
# Start an IRB session. Tries to load irb/completion, and also loads a
# .irbrc file if it exists.
def self.start
require 'irb'
begin
require 'irb/completion'
rescue Exception
# No readline available, proceed anyway.
end
if ::File.exists? ".irbrc"
ENV['IRBRC'] = ".irbrc"
end
IRB.start
end
end
end
|
bernerdschaefer/akephalos
|
dd79cf33318d70ee2852a5e632d8efc5cf4becb7
|
VERSION 0.2.5
|
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index 01e2e95..d3da043 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.2.4"
+ VERSION = "0.2.5"
end
|
bernerdschaefer/akephalos
|
48f018cb85cace5774dc7ec5f0979bce581b3976
|
Add configuration section to documentation
|
diff --git a/README.md b/README.md
index 25aa6d7..d1d4ce7 100644
--- a/README.md
+++ b/README.md
@@ -1,56 +1,86 @@
# Akephalos
Akephalos is a full-stack headless browser for integration testing with
Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
## Installation
gem install akephalos
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
require 'akephalos'
Capybara.javascript_driver = :akephalos
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
+## Configuration
+
+There are now a few configuration options available through Capybara's new
+`register_driver` API.
+
+### Using a different browser
+
+HtmlUnit supports a few browser implementations, and you can choose which
+browser you would like to use through Akephalos. By default, Akephalos uses
+Firefox 3.6.
+
+ Capybara.register_driver :akephalos do |app|
+ # available options:
+ # :ie6, :ie7, :ie8, :firefox_3, :firefox_3_6
+ Capybara::Driver::Akephalos.new(app, :browser => :ie8)
+ end
+
+### Ignoring javascript errors
+
+By default HtmlUnit (and Akephalos) will raise an exception when an error
+is encountered in javascript files. This is generally desireable, except
+that certain libraries aren't supported by HtmlUnit. If possible, it's
+best to keep the default behavior, and use Filters (see below) to mock
+offending libraries. If needed, however, you can configure Akephalos to
+ignore javascript errors.
+
+ Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app, :validate_scripts => false)
+ end
+
## More
* [bin/akephalos](http://bernerdschaefer.github.com/akephalos/akephalos-bin.html)
allows you to start an interactive shell or DRb server, as well as perform
other maintenance features.
* [Filters](http://bernerdschaefer.github.com/akephalos/filters.html) allows
you to declare mock responses for external resources and services requested
by the browser.
## Resources
* [API Documentation](http://bernerdschaefer.github.com/akephalos/api)
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
diff --git a/docs/index.html.haml b/docs/index.html.haml
index 7cdcff6..5102218 100644
--- a/docs/index.html.haml
+++ b/docs/index.html.haml
@@ -1,68 +1,106 @@
%section
:markdown
Akephalos is a full-stack headless browser for integration testing with
Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
%section
:markdown
## Installation
%aside
:bash
gem install akephalos
%section
:markdown
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
%aside
:code
require 'akephalos'
Capybara.javascript_driver = :akephalos
%section
:markdown
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
%aside
:code
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
+%section
+ :markdown
+ ## Configuration
+
+ There are now a few configuration options available through Capybara's new
+ `register_driver` API.
+
+ ### Using a different browser
+
+ HtmlUnit supports a few browser implementations, and you can choose which
+ browser you would like to use through Akephalos. By default, Akephalos uses
+ Firefox 3.6.
+
+%aside
+ :code
+ Capybara.register_driver :akephalos do |app|
+ # available options:
+ # :ie6, :ie7, :ie8, :firefox_3, :firefox_3_6
+ Capybara::Driver::Akephalos.new(app, :browser => :ie8)
+ end
+
+%section
+ :markdown
+ ### Ignoring javascript errors
+
+ By default HtmlUnit (and Akephalos) will raise an exception when an error
+ is encountered in javascript files. This is generally desireable, except
+ that certain libraries aren't supported by HtmlUnit. If possible, it's
+ best to keep the default behavior, and use Filters (see below) to mock
+ offending libraries. If needed, however, you can configure Akephalos to
+ ignore javascript errors.
+
+%aside
+ :code
+ Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app, :validate_scripts => false)
+ end
+
%section
:markdown
## More
* [bin/akephalos](akephalos-bin.html) allows you to start an interactive
shell or DRb server, as well as perform other maintenance features.
* [Filters](filters.html) allows you to declare mock responses for
external resources and services requested by the browser.
## Resources
* [API Documentation](http://bernerdschaefer.github.com/akephalos/api)
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
|
bernerdschaefer/akephalos
|
4229011ef7ec3b525b53ab2dd3ebf4301d5b677e
|
Lock capybara dependency to 0.4 series
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 9808155..1eee36a 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
- s.add_runtime_dependency "capybara", ">= 0.4.0"
+ s.add_runtime_dependency "capybara", "~> 0.4.0"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
s.add_development_dependency "rspec", ">= 2.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
44073fcfece030424418981038c6e3085cc2c5ba
|
Flag failing capybara specs as pending
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index d5e6d03..3314b9c 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,30 +1,39 @@
require 'rubygems'
root = File.expand_path('../../', __FILE__)
lib_paths = [root] + %w(vendor lib src).collect { |dir| File.join(root, dir) }
(lib_paths).each do |dir|
$:.unshift dir unless $:.include?(dir)
end
require 'akephalos'
spec_dir = nil
$:.detect do |dir|
if File.exists? File.join(dir, "capybara.rb")
spec_dir = File.expand_path(File.join(dir,"..","spec"))
$:.unshift( spec_dir )
end
end
require File.join(spec_dir,"spec_helper")
require "support/application"
RSpec.configure do |config|
running_with_jruby = RUBY_PLATFORM =~ /java/
warn "[AKEPHALOS] ** Skipping JRuby-only specs" unless running_with_jruby
+ config.before(:each, :full_description => /wait for block to return true/) do
+ pending "This spec failure is a red herring; akephalos waits for " \
+ "javascript events implicitly, including setTimeout."
+ end
+
+ config.before(:each, :full_description => /drag and drop/) do
+ pending "drag and drop is not supported yet"
+ end
+
config.filter_run_excluding(:platform => lambda { |value|
return true if value == :jruby && !running_with_jruby
})
end
|
bernerdschaefer/akephalos
|
0fbcbbf160b7f1eccae38bc4b05cf28240a97835
|
Configure browser version and javascript errors
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 23564f4..5244cb6 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,311 +1,338 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Driver::Node class.
class Node < Capybara::Driver::Node
# @api capybara
# @return [String] the inner text of the node
def text
native.text
end
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
native.checked?
else
native[name.to_s]
end
end
# @api capybara
# @return [String, Array<String>] the form element's value
def value
native.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
native.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
native.value = value.to_s
end
end
# @api capybara
def select_option
native.click
end
# Unselect an option from a select box.
#
# @api capybara
def unselect_option
unless select_node.multiple_select?
raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
end
native.unselect
end
# Click the element.
def click
native.click
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# @api capybara
# @return [String] the element's tag name
def tag_name
native.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
native.visible?
end
# @api capybara
# @return [true, false] the element's visiblity
def checked?
native.checked?
end
# @api capybara
# @return [true, false] the element's visiblity
def selected?
native.selected?
end
# @api capybara
# @return [String] the XPath to locate the node
def path
native.xpath
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
native.fire_event(event.to_s)
end
# @api capybara
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(self, node) }
nodes
end
protected
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
tag_name == "select" && native.multiple_select?
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
native[:type]
end
# @return [Node] the select node, if this is an option node
def select_node
find('./ancestor::select').first
end
end
- attr_reader :app, :rack_server
+ attr_reader :app, :rack_server, :options
- def initialize(app)
+ # Creates a new instance of the Akephalos Driver for Capybara. The driver is
+ # registered with Capybara by a name, so that it can be chosen when
+ # Capybara's javascript_driver is changed. By default, Akephalos is
+ # registered like this:
+ #
+ # Capybara.register_driver :akephalos do |app|
+ # Capybara::Akephalos::Driver.new(
+ # app,
+ # :browser => :firefox_3_6,
+ # :validate_scripts => true
+ # )
+ # end
+ #
+ # @param app the Rack application to run
+ # @param [Hash] options the Akephalos configuration options
+ # @option options [Symbol] :browser (:firefox_3_6) the browser
+ # compatibility mode to run in. Available options:
+ # :firefox_3_6
+ # :firefox_3
+ # :ie6
+ # :ie7
+ # :ie8
+ #
+ # @option options [true, false] :validate_scripts (true) whether to raise
+ # exceptions on script errors
+ #
+ def initialize(app, options = {})
@app = app
+ @options = options
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
# page.modified_source will return a string with
# html entities converted into the unicode equivalent
# but the string will be marked as ASCII-8BIT
# which causes conversion issues so we force the encoding
# to UTF-8 (ruby 1.9 only)
def body
body_source = page.modified_source
if body_source.respond_to?(:force_encoding)
body_source.force_encoding("UTF-8")
else
body_source
end
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
# {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
- @browser ||= Akephalos::Client.new
+ @browser ||= Akephalos::Client.new(@options)
end
# @return the session cookies
def cookies
browser.cookies
end
# @return [String] the current user agent string
def user_agent
browser.user_agent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
browser.user_agent = user_agent
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
Capybara.register_driver :akephalos do |app|
Capybara::Driver::Akephalos.new(app)
end
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index 15254b8..af26ec2 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,102 +1,152 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
+
+ # @return [Akephalos::Page] the current page
attr_reader :page
- def initialize
+ # @return [HtmlUnit::BrowserVersion] the configured browser version
+ attr_reader :browser_version
+
+ # @return [true/false] whether to raise errors on javascript failures
+ attr_reader :validate_scripts
+
+ # The default configuration options for a new Client.
+ DEFAULT_OPTIONS = {
+ :browser => :firefox_3_6,
+ :validate_scripts => true
+ }
+
+ # Map of browser version symbols to their HtmlUnit::BrowserVersion
+ # instances.
+ BROWSER_VERSIONS = {
+ :ie6 => HtmlUnit::BrowserVersion::INTERNET_EXPLORER_6,
+ :ie7 => HtmlUnit::BrowserVersion::INTERNET_EXPLORER_7,
+ :ie8 => HtmlUnit::BrowserVersion::INTERNET_EXPLORER_8,
+ :firefox_3 => HtmlUnit::BrowserVersion::FIREFOX_3,
+ :firefox_3_6 => HtmlUnit::BrowserVersion::FIREFOX_3_6
+ }
+
+ # @param [Hash] options the configuration options for this client
+ #
+ # @option options [Symbol] :browser (:firefox_3_6) the browser version (
+ # see BROWSER_VERSIONS)
+ #
+ # @option options [true, false] :validate_scripts (true) whether to raise
+ # errors on javascript errors
+ def initialize(options = {})
+ process_options!(options)
+
@_client = java.util.concurrent.FutureTask.new do
- client = HtmlUnit::WebClient.new
+ client = HtmlUnit::WebClient.new(browser_version)
Filter.new(client)
client.setThrowExceptionOnFailingStatusCode(false)
client.setAjaxController(HtmlUnit::NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(HtmlUnit::SilentCssErrorHandler.new)
- client.setThrowExceptionOnScriptError(false);
+ client.setThrowExceptionOnScriptError(validate_scripts)
client
end
Thread.new { @_client.run }
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
# @return [Cookies] the cookies for this session
def cookies
@cookies ||= Cookies.new(client.getCookieManager)
end
# @return [String] the current user agent string
def user_agent
@user_agent || client.getBrowserVersion.getUserAgent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
if user_agent == :default
@user_agent = nil
client.removeRequestHeader("User-Agent")
else
@user_agent = user_agent
client.addRequestHeader("User-Agent", user_agent)
end
end
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
+ # @return [true, false] whether javascript errors will raise exceptions
+ def validate_scripts?
+ !!validate_scripts
+ end
+
+ # Merges the DEFAULT_OPTIONS with those provided to initialize the Client
+ # state, namely, its browser version and whether it should
+ # validate scripts.
+ #
+ # @param [Hash] options the options to process
+ def process_options!(options)
+ options = DEFAULT_OPTIONS.merge(options)
+
+ @browser_version = BROWSER_VERSIONS.fetch(options.delete(:browser))
+ @validate_scripts = options.delete(:validate_scripts)
+ end
+
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/lib/akephalos/htmlunit.rb b/lib/akephalos/htmlunit.rb
index 072b142..6f9b042 100644
--- a/lib/akephalos/htmlunit.rb
+++ b/lib/akephalos/htmlunit.rb
@@ -1,38 +1,35 @@
require "pathname"
require "java"
dependency_directory = $:.detect { |path| Dir[File.join(path, 'htmlunit/htmlunit-*.jar')].any? }
raise "Could not find htmlunit/htmlunit-VERSION.jar in load path:\n [ #{$:.join(",\n ")}\n ]" unless dependency_directory
Dir[File.join(dependency_directory, "htmlunit/*.jar")].each do |jar|
require jar
end
java.lang.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog")
java.lang.System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "fatal")
java.lang.System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true")
# Container module for com.gargoylesoftware.htmlunit namespace.
module HtmlUnit
java_import "com.gargoylesoftware.htmlunit.BrowserVersion"
java_import "com.gargoylesoftware.htmlunit.History"
java_import "com.gargoylesoftware.htmlunit.HttpMethod"
java_import "com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController"
java_import "com.gargoylesoftware.htmlunit.SilentCssErrorHandler"
java_import "com.gargoylesoftware.htmlunit.WebClient"
java_import "com.gargoylesoftware.htmlunit.WebResponseData"
java_import "com.gargoylesoftware.htmlunit.WebResponseImpl"
# Container module for com.gargoylesoftware.htmlunit.util namespace.
module Util
java_import "com.gargoylesoftware.htmlunit.util.NameValuePair"
java_import "com.gargoylesoftware.htmlunit.util.WebConnectionWrapper"
end
# Disable history tracking
History.field_reader :ignoreNewPages_
-
- # Run in Firefox compatibility mode
- BrowserVersion.setDefault(BrowserVersion::FIREFOX_3)
end
diff --git a/lib/akephalos/remote_client.rb b/lib/akephalos/remote_client.rb
index a277927..5379ac6 100644
--- a/lib/akephalos/remote_client.rb
+++ b/lib/akephalos/remote_client.rb
@@ -1,92 +1,92 @@
require 'socket'
require 'drb/drb'
# We need to define our own NativeException class for the cases when a native
# exception is raised by the JRuby DRb server.
class NativeException < StandardError; end
module Akephalos
# The +RemoteClient+ class provides an interface to an +Akephalos::Client+
# isntance on a remote DRb server.
#
# == Usage
# client = Akephalos::RemoteClient.new
# client.visit "http://www.oinopa.com"
# client.page.source # => "<!DOCTYPE html PUBLIC..."
class RemoteClient
# @return [DRbObject] a new instance of Akephalos::Client from the DRb
# server
- def self.new
- manager.new_client
+ def self.new(options = {})
+ manager.new_client(options)
end
# Starts a remove JRuby DRb server unless already running and returns an
# instance of Akephalos::ClientManager.
#
- # @returns [DRbObject] an instance of Akephalos::ClientManager
+ # @return [DRbObject] an instance of Akephalos::ClientManager
def self.manager
return @manager if defined?(@manager)
server_port = start!
DRb.start_service
manager = DRbObject.new_with_uri("druby://127.0.0.1:#{server_port}")
# We want to share our local configuration with the remote server
# process, so we share an undumped version of our configuration. This
# lets us continue to make changes locally and have them reflected in the
# remote process.
manager.configuration = Akephalos.configuration.extend(DRbUndumped)
@manager = manager
end
# Start a remote server process and return when it is available for use.
def self.start!
port = find_available_port
remote_client = IO.popen("#{Akephalos::BIN_DIR + 'akephalos'} #{port}")
# Set up a monitor thread to detect if the forked server exits
# prematurely.
server_monitor = Thread.new { Thread.current[:exited] = Process.wait(remote_client.pid) }
# Wait for the server to be accessible on the socket we specified.
until responsive?(port)
exit!(1) if server_monitor[:exited]
sleep 0.5
end
server_monitor.kill
# Ensure that the remote server shuts down gracefully when we are
# finished.
at_exit { Process.kill(:INT, remote_client.pid) }
port
end
private
# @api private
# @param [Integer] port the port to check for responsiveness
# @return [true, false] whether the port is responsive
def self.responsive?(port)
socket = TCPSocket.open('127.0.0.1', port)
true
rescue Errno::ECONNREFUSED
false
ensure
socket.close if socket
end
# @api private
# @return [Integer] the next available port
def self.find_available_port
server = TCPServer.new('127.0.0.1', 0)
server.addr[1]
ensure
server.close if server
end
end
end
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index cfa7c5f..611b845 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,79 +1,79 @@
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
# @note This method is called by DRb before sending the error to the remote
# connection.
# @return [String] the inner message.
def _dump
to_s
end
end
[
Akephalos::Page,
Akephalos::Node,
Akephalos::Client::Cookies,
Akephalos::Client::Cookies::Cookie
].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
# The ClientManager is shared over DRb with the remote process, and
# facilitates communication between the processes.
#
# @api private
class ClientManager
include DRbUndumped
# @return [Akephalos::Client] a new client instance
- def self.new_client
+ def self.new_client(options = {})
# Store the client to ensure it isn't prematurely garbage collected.
- @client = Client.new
+ @client = Client.new(options)
end
# Set the global configuration settings for Akephalos.
#
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def self.configuration=(config)
Akephalos.configuration = config
end
end
# Akephalos::Server is used by `akephalos --server` to start a DRb server
# serving Akephalos::ClientManager.
class Server
# Start DRb service for Akephalos::ClientManager.
#
# @param [String] port attach server to
def self.start!(port)
abort_on_parent_exit!
DRb.start_service("druby://127.0.0.1:#{port}", ClientManager)
DRb.thread.join
end
private
# Exit if STDIN is no longer readable, which corresponds to the process
# which started the server exiting prematurely.
#
# @api private
def self.abort_on_parent_exit!
Thread.new do
begin
STDIN.read
rescue IOError
exit
end
end
end
end
end
diff --git a/spec/integration/browser_version_spec.rb b/spec/integration/browser_version_spec.rb
new file mode 100644
index 0000000..67f3eed
--- /dev/null
+++ b/spec/integration/browser_version_spec.rb
@@ -0,0 +1,66 @@
+require 'spec_helper'
+
+describe Capybara::Driver::Akephalos do
+
+ let(:session) { Capybara::Session.new(:akephalos, Application) }
+
+ before do
+ @original_driver = Capybara.drivers.delete(:akephalos)
+ end
+
+ after do
+ Capybara.drivers[:akephalos] = @original_driver
+ end
+
+ describe "visiting a page with browser specific content" do
+ context "when in IE6 mode" do
+ before do
+ Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app, :browser => :ie6)
+ end
+ end
+
+ it "renders IE6 content" do
+ session.visit "/ie_test"
+ session.should have_content("InternetExplorer6")
+ end
+
+ it "does not render other content" do
+ session.visit "/ie_test"
+ session.should_not have_content("InternetExplorer7")
+ end
+ end
+
+ context "when in IE7 mode" do
+ before do
+ Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app, :browser => :ie7)
+ end
+ end
+
+ it "renders IE7 content" do
+ session.visit "/ie_test"
+ session.should have_content("InternetExplorer7")
+ end
+
+ it "does not render other content" do
+ session.visit "/ie_test"
+ session.should_not have_content("InternetExplorer6")
+ end
+ end
+
+ context "when in Firefox mode" do
+ before do
+ Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app, :browser => :firefox_3_6)
+ end
+ end
+
+ it "does not render IE content" do
+ session.visit "/ie_test"
+ session.should_not have_content("InternetExplorer")
+ end
+ end
+ end
+
+end
diff --git a/spec/integration/script_errors_spec.rb b/spec/integration/script_errors_spec.rb
new file mode 100644
index 0000000..e64271f
--- /dev/null
+++ b/spec/integration/script_errors_spec.rb
@@ -0,0 +1,38 @@
+require 'spec_helper'
+
+describe Capybara::Driver::Akephalos do
+
+ describe "visiting a page with a javascript error" do
+ context "with script validation enabled" do
+
+ let(:driver) do
+ Capybara::Driver::Akephalos.new(Application)
+ end
+
+ it "raises an exception" do
+ running do
+ driver.visit "/page_with_javascript_error"
+ end.should raise_error
+ end
+
+ end
+
+ context "with script validation disabled" do
+
+ let(:driver) do
+ Capybara::Driver::Akephalos.new(
+ Application,
+ :validate_scripts => false
+ )
+ end
+
+ it "ignores the error" do
+ running do
+ driver.visit "/page_with_javascript_error"
+ end.should_not raise_error
+ end
+
+ end
+ end
+
+end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index ef7e4a0..d5e6d03 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,20 +1,30 @@
require 'rubygems'
root = File.expand_path('../../', __FILE__)
lib_paths = [root] + %w(vendor lib src).collect { |dir| File.join(root, dir) }
(lib_paths).each do |dir|
$:.unshift dir unless $:.include?(dir)
end
require 'akephalos'
spec_dir = nil
$:.detect do |dir|
if File.exists? File.join(dir, "capybara.rb")
spec_dir = File.expand_path(File.join(dir,"..","spec"))
$:.unshift( spec_dir )
end
end
require File.join(spec_dir,"spec_helper")
require "support/application"
+
+RSpec.configure do |config|
+ running_with_jruby = RUBY_PLATFORM =~ /java/
+
+ warn "[AKEPHALOS] ** Skipping JRuby-only specs" unless running_with_jruby
+
+ config.filter_run_excluding(:platform => lambda { |value|
+ return true if value == :jruby && !running_with_jruby
+ })
+end
diff --git a/spec/support/application.rb b/spec/support/application.rb
index 452f065..e2b6128 100644
--- a/spec/support/application.rb
+++ b/spec/support/application.rb
@@ -1,40 +1,68 @@
class Application < TestApp
get '/slow_page' do
sleep 1
"<p>Loaded!</p>"
end
get '/slow_ajax_load' do
<<-HTML
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>with_js</title>
<script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$('#ajax_load').click(function() {
$('body').load('/slow_page');
return false;
});
});
</script>
</head>
<body>
<a href="#" id="ajax_load">Click me</a>
</body>
- HTML
+ HTML
end
get '/user_agent_detection' do
request.user_agent
end
get '/app_domain_detection' do
"http://#{request.host_with_port}/app_domain_detection"
end
+
+ get '/page_with_javascript_error' do
+ <<-HTML
+ <head>
+ <script type="text/javascript">
+ $() // is not defined
+ </script>
+ </head>
+ <body>
+ </body>
+ HTML
+ end
+
+ get '/ie_test' do
+ <<-HTML
+ <body>
+ <!--[if IE 6]>
+ This is for InternetExplorer6
+ <![endif]-->
+ <!--[if IE 7]>
+ This is for InternetExplorer7
+ <![endif]-->
+ <!--[if IE 8]>
+ This is for InternetExplorer8
+ <![endif]-->
+ </body>
+ HTML
+ end
end
if $0 == __FILE__
Rack::Handler::Mongrel.run Application, :Port => 8070
end
diff --git a/spec/unit/client_spec.rb b/spec/unit/client_spec.rb
new file mode 100644
index 0000000..9ffd3be
--- /dev/null
+++ b/spec/unit/client_spec.rb
@@ -0,0 +1,48 @@
+require 'spec_helper'
+
+describe Akephalos::Client, :platform => :jruby do
+
+ context "browser version" do
+
+ it "defaults to Firefox 3.6" do
+ client = Akephalos::Client.new
+ client.browser_version.should ==
+ HtmlUnit::BrowserVersion::FIREFOX_3_6
+ end
+
+ it "can be configured in the initializer" do
+ client = Akephalos::Client.new(:browser => :ie6)
+ client.browser_version.should ==
+ HtmlUnit::BrowserVersion::INTERNET_EXPLORER_6
+ end
+
+ it "configures HtmlUnit" do
+ client = Akephalos::Client.new(:browser => :ie7)
+
+ client.send(:client).getBrowserVersion.should ==
+ HtmlUnit::BrowserVersion::INTERNET_EXPLORER_7
+ end
+
+ end
+
+ context "script validation" do
+
+ it "defaults to raising errors on script execution" do
+ Akephalos::Client.new.validate_scripts?.should be_true
+ end
+
+ it "can be configured not to raise errors on script execution" do
+ Akephalos::Client.new(
+ :validate_scripts => false
+ ).validate_scripts?.should be_false
+ end
+
+ it "configures HtmlUnit" do
+ client = Akephalos::Client.new(:validate_scripts => false)
+
+ client.send(:client).isThrowExceptionOnScriptError.should be_false
+ end
+
+ end
+
+end
|
bernerdschaefer/akephalos
|
4ed46eadaf1299d6a4d6dfe5c442ddd078674562
|
Add Akephalos::ClientManager for DRb Server
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index b33430c..23564f4 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,316 +1,311 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Driver::Node class.
class Node < Capybara::Driver::Node
# @api capybara
# @return [String] the inner text of the node
def text
native.text
end
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
native.checked?
else
native[name.to_s]
end
end
# @api capybara
# @return [String, Array<String>] the form element's value
def value
native.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
native.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
native.value = value.to_s
end
end
# @api capybara
def select_option
native.click
end
# Unselect an option from a select box.
#
# @api capybara
def unselect_option
unless select_node.multiple_select?
raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
end
native.unselect
end
# Click the element.
def click
native.click
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# @api capybara
# @return [String] the element's tag name
def tag_name
native.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
native.visible?
end
# @api capybara
# @return [true, false] the element's visiblity
def checked?
native.checked?
end
# @api capybara
# @return [true, false] the element's visiblity
def selected?
native.selected?
end
# @api capybara
# @return [String] the XPath to locate the node
def path
native.xpath
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
native.fire_event(event.to_s)
end
# @api capybara
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(self, node) }
nodes
end
protected
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
tag_name == "select" && native.multiple_select?
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
native[:type]
end
# @return [Node] the select node, if this is an option node
def select_node
find('./ancestor::select').first
end
end
attr_reader :app, :rack_server
- # @return [Client] an instance of Akephalos::Client
- def self.driver
- @driver ||= Akephalos::Client.new
- end
-
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
# page.modified_source will return a string with
# html entities converted into the unicode equivalent
# but the string will be marked as ASCII-8BIT
# which causes conversion issues so we force the encoding
# to UTF-8 (ruby 1.9 only)
def body
body_source = page.modified_source
if body_source.respond_to?(:force_encoding)
body_source.force_encoding("UTF-8")
else
body_source
end
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
# {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
- self.class.driver
+ @browser ||= Akephalos::Client.new
end
# @return the session cookies
def cookies
browser.cookies
end
# @return [String] the current user agent string
def user_agent
browser.user_agent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
browser.user_agent = user_agent
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
Capybara.register_driver :akephalos do |app|
Capybara::Driver::Akephalos.new(app)
end
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index 48c3e47..15254b8 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,112 +1,102 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = HtmlUnit::WebClient.new
Filter.new(client)
client.setThrowExceptionOnFailingStatusCode(false)
client.setAjaxController(HtmlUnit::NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(HtmlUnit::SilentCssErrorHandler.new)
client.setThrowExceptionOnScriptError(false);
client
end
Thread.new { @_client.run }
end
- # Set the global configuration settings for Akephalos.
- #
- # @note This is only used when communicating over DRb, since just a
- # single client instance is exposed.
- # @param [Hash] config the configuration settings
- # @return [Hash] the configuration
- def configuration=(config)
- Akephalos.configuration = config
- end
-
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
# @return [Cookies] the cookies for this session
def cookies
@cookies ||= Cookies.new(client.getCookieManager)
end
# @return [String] the current user agent string
def user_agent
@user_agent || client.getBrowserVersion.getUserAgent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
if user_agent == :default
@user_agent = nil
client.removeRequestHeader("User-Agent")
else
@user_agent = user_agent
client.addRequestHeader("User-Agent", user_agent)
end
end
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/lib/akephalos/remote_client.rb b/lib/akephalos/remote_client.rb
index 1fbc94b..a277927 100644
--- a/lib/akephalos/remote_client.rb
+++ b/lib/akephalos/remote_client.rb
@@ -1,84 +1,92 @@
require 'socket'
require 'drb/drb'
# We need to define our own NativeException class for the cases when a native
# exception is raised by the JRuby DRb server.
class NativeException < StandardError; end
module Akephalos
# The +RemoteClient+ class provides an interface to an +Akephalos::Client+
# isntance on a remote DRb server.
#
# == Usage
# client = Akephalos::RemoteClient.new
# client.visit "http://www.oinopa.com"
# client.page.source # => "<!DOCTYPE html PUBLIC..."
class RemoteClient
- # Start a remote akephalos server and return the remote Akephalos::Client
- # instance.
- #
- # @return [DRbObject] the remote client instance
+ # @return [DRbObject] a new instance of Akephalos::Client from the DRb
+ # server
def self.new
+ manager.new_client
+ end
+
+ # Starts a remove JRuby DRb server unless already running and returns an
+ # instance of Akephalos::ClientManager.
+ #
+ # @returns [DRbObject] an instance of Akephalos::ClientManager
+ def self.manager
+ return @manager if defined?(@manager)
+
server_port = start!
- DRb.start_service("druby://127.0.0.1:#{find_available_port}")
- client = DRbObject.new_with_uri("druby://127.0.0.1:#{server_port}")
+ DRb.start_service
+ manager = DRbObject.new_with_uri("druby://127.0.0.1:#{server_port}")
# We want to share our local configuration with the remote server
# process, so we share an undumped version of our configuration. This
# lets us continue to make changes locally and have them reflected in the
# remote process.
- client.configuration = Akephalos.configuration.extend(DRbUndumped)
+ manager.configuration = Akephalos.configuration.extend(DRbUndumped)
- client
+ @manager = manager
end
# Start a remote server process and return when it is available for use.
def self.start!
port = find_available_port
remote_client = IO.popen("#{Akephalos::BIN_DIR + 'akephalos'} #{port}")
# Set up a monitor thread to detect if the forked server exits
# prematurely.
server_monitor = Thread.new { Thread.current[:exited] = Process.wait(remote_client.pid) }
# Wait for the server to be accessible on the socket we specified.
until responsive?(port)
exit!(1) if server_monitor[:exited]
sleep 0.5
end
server_monitor.kill
# Ensure that the remote server shuts down gracefully when we are
# finished.
at_exit { Process.kill(:INT, remote_client.pid) }
port
end
private
# @api private
# @param [Integer] port the port to check for responsiveness
# @return [true, false] whether the port is responsive
def self.responsive?(port)
socket = TCPSocket.open('127.0.0.1', port)
true
rescue Errno::ECONNREFUSED
false
ensure
socket.close if socket
end
# @api private
# @return [Integer] the next available port
def self.find_available_port
server = TCPServer.new('127.0.0.1', 0)
server.addr[1]
ensure
server.close if server
end
end
end
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index 805bafd..cfa7c5f 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,56 +1,79 @@
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
# @note This method is called by DRb before sending the error to the remote
# connection.
# @return [String] the inner message.
def _dump
to_s
end
end
[
Akephalos::Page,
Akephalos::Node,
Akephalos::Client::Cookies,
Akephalos::Client::Cookies::Cookie
].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
+ # The ClientManager is shared over DRb with the remote process, and
+ # facilitates communication between the processes.
+ #
+ # @api private
+ class ClientManager
+ include DRbUndumped
+
+ # @return [Akephalos::Client] a new client instance
+ def self.new_client
+ # Store the client to ensure it isn't prematurely garbage collected.
+ @client = Client.new
+ end
+
+ # Set the global configuration settings for Akephalos.
+ #
+ # @param [Hash] config the configuration settings
+ # @return [Hash] the configuration
+ def self.configuration=(config)
+ Akephalos.configuration = config
+ end
+
+ end
+
# Akephalos::Server is used by `akephalos --server` to start a DRb server
- # serving an instance of Akephalos::Client.
+ # serving Akephalos::ClientManager.
class Server
- # Start DRb service for an Akephalos::Client.
+
+ # Start DRb service for Akephalos::ClientManager.
#
# @param [String] port attach server to
def self.start!(port)
abort_on_parent_exit!
- client = Client.new
- DRb.start_service("druby://127.0.0.1:#{port}", client)
+ DRb.start_service("druby://127.0.0.1:#{port}", ClientManager)
DRb.thread.join
end
private
# Exit if STDIN is no longer readable, which corresponds to the process
# which started the server exiting prematurely.
#
# @api private
def self.abort_on_parent_exit!
Thread.new do
begin
STDIN.read
rescue IOError
exit
end
end
end
end
end
|
bernerdschaefer/akephalos
|
c06d869879ce38a7dc8c35a48933fb2589195506
|
Whitespace fix
|
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index b5d918b..48c3e47 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,112 +1,112 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = HtmlUnit::WebClient.new
- Filter.new(client)
+ Filter.new(client)
client.setThrowExceptionOnFailingStatusCode(false)
client.setAjaxController(HtmlUnit::NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(HtmlUnit::SilentCssErrorHandler.new)
client.setThrowExceptionOnScriptError(false);
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
# @return [Cookies] the cookies for this session
def cookies
@cookies ||= Cookies.new(client.getCookieManager)
end
# @return [String] the current user agent string
def user_agent
@user_agent || client.getBrowserVersion.getUserAgent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
if user_agent == :default
@user_agent = nil
client.removeRequestHeader("User-Agent")
else
@user_agent = user_agent
client.addRequestHeader("User-Agent", user_agent)
end
end
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
|
bernerdschaefer/akephalos
|
b8453dca07f9700cf2bad304fbfac553ceba47b0
|
See https://github.com/bernerdschaefer/akephalos/issues#issue/7
|
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index aeef0ec..b5d918b 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,111 +1,112 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = HtmlUnit::WebClient.new
- Filter.new(client)
+ Filter.new(client)
+ client.setThrowExceptionOnFailingStatusCode(false)
client.setAjaxController(HtmlUnit::NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(HtmlUnit::SilentCssErrorHandler.new)
-
+ client.setThrowExceptionOnScriptError(false);
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
# @return [Cookies] the cookies for this session
def cookies
@cookies ||= Cookies.new(client.getCookieManager)
end
# @return [String] the current user agent string
def user_agent
@user_agent || client.getBrowserVersion.getUserAgent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
if user_agent == :default
@user_agent = nil
client.removeRequestHeader("User-Agent")
else
@user_agent = user_agent
client.addRequestHeader("User-Agent", user_agent)
end
end
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
|
bernerdschaefer/akephalos
|
b3e20d7abe417c6f655199209511f5099838817c
|
Remove Gemfile.lock from the repo and git-ignore it
|
diff --git a/.gitignore b/.gitignore
index f174350..a4615c2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,9 @@
.bundle/
.rvmrc
.yardoc
burn
+Gemfile.lock
docs/build
pkg
tags
.idea/
diff --git a/Gemfile.lock b/Gemfile.lock
deleted file mode 100644
index a51a4b9..0000000
--- a/Gemfile.lock
+++ /dev/null
@@ -1,64 +0,0 @@
-PATH
- remote: .
- specs:
- akephalos (0.2.4)
- capybara (>= 0.4.0)
- jruby-jars
-
-GEM
- remote: http://rubygems.org/
- specs:
- capybara (0.4.1.1)
- celerity (>= 0.7.9)
- culerity (>= 0.2.4)
- mime-types (>= 1.16)
- nokogiri (>= 1.3.3)
- rack (>= 1.0.0)
- rack-test (>= 0.5.4)
- selenium-webdriver (>= 0.0.27)
- xpath (~> 0.1.3)
- celerity (0.8.7)
- childprocess (0.1.6)
- ffi (~> 0.6.3)
- culerity (0.2.15)
- diff-lcs (1.1.2)
- ffi (0.6.3)
- rake (>= 0.8.7)
- jruby-jars (1.5.6)
- json_pure (1.5.1)
- mime-types (1.16)
- nokogiri (1.4.4)
- rack (1.2.1)
- rack-test (0.5.7)
- rack (>= 1.0)
- rake (0.8.7)
- rspec (2.4.0)
- rspec-core (~> 2.4.0)
- rspec-expectations (~> 2.4.0)
- rspec-mocks (~> 2.4.0)
- rspec-core (2.4.0)
- rspec-expectations (2.4.0)
- diff-lcs (~> 1.1.2)
- rspec-mocks (2.4.0)
- rubyzip (0.9.4)
- selenium-webdriver (0.1.2)
- childprocess (~> 0.1.5)
- ffi (~> 0.6.3)
- json_pure
- rubyzip
- sinatra (1.1.2)
- rack (~> 1.1)
- tilt (~> 1.2)
- tilt (1.2.2)
- xpath (0.1.3)
- nokogiri (~> 1.3)
-
-PLATFORMS
- ruby
-
-DEPENDENCIES
- akephalos!
- capybara (>= 0.4.0)
- jruby-jars
- rspec (>= 2.3.0)
- sinatra
|
bernerdschaefer/akephalos
|
0936eeae59b89df15c914cbb33c1a4b633bda3cd
|
certain elements do not respond to isChecked or isSelected so look at their attributes
|
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index 06ced83..2f66ddd 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,162 +1,172 @@
module Akephalos
# Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
# interacting with an element on the page.
class Node
# @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
# @return [true, false] whether the element is checked
def checked?
- @_node.isChecked
+ if @_node.respond_to?(:isChecked)
+ @_node.isChecked
+ else
+ !! self[:checked]
+ end
end
# @return [String] inner text of the node
def text
@_node.asText
end
# Return the value of the node's attribute.
#
# @param [String] name attribute on node
# @return [String] the value of the named attribute
# @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
# Return the value of a form element. If the element is a select box and
# has "multiple" declared as an attribute, then all selected options will
# be returned as an array.
#
# @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
selected_options.map { |option| option.value }
else
selected_option = @_node.selected_options.first
selected_option ? Node.new(selected_option).value : nil
end
when "option"
self[:value] || text
when "textarea"
@_node.getText
else
self[:value]
end
end
# Set the value of the form input.
#
# @param [String] value
def value=(value)
case tag_name
when "textarea"
@_node.setText("")
type(value)
when "input"
if file_input?
@_node.setValueAttribute(value)
else
@_node.setValueAttribute("")
type(value)
end
end
end
# Types each character into a text or input field.
#
# @param [String] value the string to type
def type(value)
value.each_char do |c|
@_node.type(c)
end
end
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
!self[:multiple].nil?
end
# @return [true, false] whether the node is a file input
def file_input?
tag_name == "input" && @_node.getAttribute("type") == "file"
end
# Unselect an option.
#
# @return [true, false] whether the unselection was successful
def unselect
@_node.setSelected(false)
end
# Return the option elements for a select box.
#
# @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
# Return the selected option elements for a select box.
#
# @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
# Fire a JavaScript event on the current node. Note that you should not
# prefix event names with "on", so:
#
# link.fire_event('mousedown')
#
# @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
# @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
# @return [true, false] whether the node is visible to the user accounting
# for CSS.
def visible?
@_node.isDisplayed
end
+ # @return [true, false] whether the node is selected to the user accounting
+ # for CSS.
def selected?
- @_node.isSelected
+ if @_node.respond_to?(:isSelected)
+ @_node.isSelected
+ else
+ !! self[:selected]
+ end
end
# Click the node and then wait for any triggered JavaScript callbacks to
# fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
# Search for child nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
# @return [String] the XPath expression for this node
def xpath
@_node.getCanonicalXPath
end
end
end
|
bernerdschaefer/akephalos
|
1a5e59ec28b3db94e26562d532dc73825b8d7bd3
|
fix conversion issue with html entities in ruby 1.9
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 99690bb..b33430c 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,305 +1,316 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Driver::Node class.
class Node < Capybara::Driver::Node
# @api capybara
# @return [String] the inner text of the node
def text
native.text
end
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
native.checked?
else
native[name.to_s]
end
end
# @api capybara
# @return [String, Array<String>] the form element's value
def value
native.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
native.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
native.value = value.to_s
end
end
# @api capybara
def select_option
native.click
end
# Unselect an option from a select box.
#
# @api capybara
def unselect_option
unless select_node.multiple_select?
raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
end
native.unselect
end
# Click the element.
def click
native.click
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# @api capybara
# @return [String] the element's tag name
def tag_name
native.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
native.visible?
end
# @api capybara
# @return [true, false] the element's visiblity
def checked?
native.checked?
end
# @api capybara
# @return [true, false] the element's visiblity
def selected?
native.selected?
end
# @api capybara
# @return [String] the XPath to locate the node
def path
native.xpath
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
native.fire_event(event.to_s)
end
# @api capybara
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(self, node) }
nodes
end
protected
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
tag_name == "select" && native.multiple_select?
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
native[:type]
end
# @return [Node] the select node, if this is an option node
def select_node
find('./ancestor::select').first
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
+ # page.modified_source will return a string with
+ # html entities converted into the unicode equivalent
+ # but the string will be marked as ASCII-8BIT
+ # which causes conversion issues so we force the encoding
+ # to UTF-8 (ruby 1.9 only)
def body
- page.modified_source
+ body_source = page.modified_source
+
+ if body_source.respond_to?(:force_encoding)
+ body_source.force_encoding("UTF-8")
+ else
+ body_source
+ end
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
# {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# @return the session cookies
def cookies
browser.cookies
end
# @return [String] the current user agent string
def user_agent
browser.user_agent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
browser.user_agent = user_agent
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
Capybara.register_driver :akephalos do |app|
Capybara::Driver::Akephalos.new(app)
end
|
bernerdschaefer/akephalos
|
8e6c87095a0fdd5d5968ed15961f1bf52823039f
|
add selected? method
|
diff --git a/Gemfile.lock b/Gemfile.lock
index 8410030..a51a4b9 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,62 +1,64 @@
PATH
remote: .
specs:
akephalos (0.2.4)
capybara (>= 0.4.0)
jruby-jars
GEM
remote: http://rubygems.org/
specs:
capybara (0.4.1.1)
celerity (>= 0.7.9)
culerity (>= 0.2.4)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (>= 0.0.27)
xpath (~> 0.1.3)
celerity (0.8.7)
childprocess (0.1.6)
ffi (~> 0.6.3)
culerity (0.2.15)
diff-lcs (1.1.2)
ffi (0.6.3)
rake (>= 0.8.7)
jruby-jars (1.5.6)
json_pure (1.5.1)
mime-types (1.16)
nokogiri (1.4.4)
rack (1.2.1)
rack-test (0.5.7)
rack (>= 1.0)
rake (0.8.7)
rspec (2.4.0)
rspec-core (~> 2.4.0)
rspec-expectations (~> 2.4.0)
rspec-mocks (~> 2.4.0)
rspec-core (2.4.0)
rspec-expectations (2.4.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.4.0)
rubyzip (0.9.4)
selenium-webdriver (0.1.2)
childprocess (~> 0.1.5)
ffi (~> 0.6.3)
json_pure
rubyzip
sinatra (1.1.2)
rack (~> 1.1)
tilt (~> 1.2)
tilt (1.2.2)
xpath (0.1.3)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
akephalos!
+ capybara (>= 0.4.0)
+ jruby-jars
rspec (>= 2.3.0)
sinatra
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index e38b52d..99690bb 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,293 +1,305 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Driver::Node class.
class Node < Capybara::Driver::Node
# @api capybara
# @return [String] the inner text of the node
def text
native.text
end
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
native.checked?
else
native[name.to_s]
end
end
# @api capybara
# @return [String, Array<String>] the form element's value
def value
native.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
native.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
native.value = value.to_s
end
end
# @api capybara
def select_option
native.click
end
# Unselect an option from a select box.
#
# @api capybara
def unselect_option
unless select_node.multiple_select?
raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
end
native.unselect
end
# Click the element.
def click
native.click
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# @api capybara
# @return [String] the element's tag name
def tag_name
native.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
native.visible?
end
+ # @api capybara
+ # @return [true, false] the element's visiblity
+ def checked?
+ native.checked?
+ end
+
+ # @api capybara
+ # @return [true, false] the element's visiblity
+ def selected?
+ native.selected?
+ end
+
# @api capybara
# @return [String] the XPath to locate the node
def path
native.xpath
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
native.fire_event(event.to_s)
end
# @api capybara
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(self, node) }
nodes
end
protected
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
tag_name == "select" && native.multiple_select?
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
native.find(selector).each { |node| nodes << self.class.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
native[:type]
end
# @return [Node] the select node, if this is an option node
def select_node
find('./ancestor::select').first
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
# {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# @return the session cookies
def cookies
browser.cookies
end
# @return [String] the current user agent string
def user_agent
browser.user_agent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
browser.user_agent = user_agent
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
Capybara.register_driver :akephalos do |app|
Capybara::Driver::Akephalos.new(app)
end
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index f65c47e..06ced83 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,158 +1,162 @@
module Akephalos
# Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
# interacting with an element on the page.
class Node
# @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
# @return [true, false] whether the element is checked
def checked?
@_node.isChecked
end
# @return [String] inner text of the node
def text
@_node.asText
end
# Return the value of the node's attribute.
#
# @param [String] name attribute on node
# @return [String] the value of the named attribute
# @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
# Return the value of a form element. If the element is a select box and
# has "multiple" declared as an attribute, then all selected options will
# be returned as an array.
#
# @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
selected_options.map { |option| option.value }
else
selected_option = @_node.selected_options.first
selected_option ? Node.new(selected_option).value : nil
end
when "option"
self[:value] || text
when "textarea"
@_node.getText
else
self[:value]
end
end
# Set the value of the form input.
#
# @param [String] value
def value=(value)
case tag_name
when "textarea"
@_node.setText("")
type(value)
when "input"
if file_input?
@_node.setValueAttribute(value)
else
@_node.setValueAttribute("")
type(value)
end
end
end
# Types each character into a text or input field.
#
# @param [String] value the string to type
def type(value)
value.each_char do |c|
@_node.type(c)
end
end
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
!self[:multiple].nil?
end
# @return [true, false] whether the node is a file input
def file_input?
tag_name == "input" && @_node.getAttribute("type") == "file"
end
-
+
# Unselect an option.
#
# @return [true, false] whether the unselection was successful
def unselect
@_node.setSelected(false)
end
# Return the option elements for a select box.
#
# @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
# Return the selected option elements for a select box.
#
# @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
# Fire a JavaScript event on the current node. Note that you should not
# prefix event names with "on", so:
#
# link.fire_event('mousedown')
#
# @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
# @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
# @return [true, false] whether the node is visible to the user accounting
# for CSS.
def visible?
@_node.isDisplayed
end
+ def selected?
+ @_node.isSelected
+ end
+
# Click the node and then wait for any triggered JavaScript callbacks to
# fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
# Search for child nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
-
+
# @return [String] the XPath expression for this node
def xpath
@_node.getCanonicalXPath
end
end
end
|
bernerdschaefer/akephalos
|
2b580dcbc13eb17b7ee1667f009b6c33383d4b07
|
Remove Gemfile.lock from gitignore
|
diff --git a/.gitignore b/.gitignore
index 776c7fb..f174350 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,8 @@
.bundle/
.rvmrc
.yardoc
-Gemfile.lock
burn
docs/build
pkg
tags
-
.idea/
diff --git a/Gemfile.lock b/Gemfile.lock
new file mode 100644
index 0000000..8410030
--- /dev/null
+++ b/Gemfile.lock
@@ -0,0 +1,62 @@
+PATH
+ remote: .
+ specs:
+ akephalos (0.2.4)
+ capybara (>= 0.4.0)
+ jruby-jars
+
+GEM
+ remote: http://rubygems.org/
+ specs:
+ capybara (0.4.1.1)
+ celerity (>= 0.7.9)
+ culerity (>= 0.2.4)
+ mime-types (>= 1.16)
+ nokogiri (>= 1.3.3)
+ rack (>= 1.0.0)
+ rack-test (>= 0.5.4)
+ selenium-webdriver (>= 0.0.27)
+ xpath (~> 0.1.3)
+ celerity (0.8.7)
+ childprocess (0.1.6)
+ ffi (~> 0.6.3)
+ culerity (0.2.15)
+ diff-lcs (1.1.2)
+ ffi (0.6.3)
+ rake (>= 0.8.7)
+ jruby-jars (1.5.6)
+ json_pure (1.5.1)
+ mime-types (1.16)
+ nokogiri (1.4.4)
+ rack (1.2.1)
+ rack-test (0.5.7)
+ rack (>= 1.0)
+ rake (0.8.7)
+ rspec (2.4.0)
+ rspec-core (~> 2.4.0)
+ rspec-expectations (~> 2.4.0)
+ rspec-mocks (~> 2.4.0)
+ rspec-core (2.4.0)
+ rspec-expectations (2.4.0)
+ diff-lcs (~> 1.1.2)
+ rspec-mocks (2.4.0)
+ rubyzip (0.9.4)
+ selenium-webdriver (0.1.2)
+ childprocess (~> 0.1.5)
+ ffi (~> 0.6.3)
+ json_pure
+ rubyzip
+ sinatra (1.1.2)
+ rack (~> 1.1)
+ tilt (~> 1.2)
+ tilt (1.2.2)
+ xpath (0.1.3)
+ nokogiri (~> 1.3)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ akephalos!
+ rspec (>= 2.3.0)
+ sinatra
|
bernerdschaefer/akephalos
|
66d3b596166f3ad9eb2f8ba00f634cc6f89b6093
|
Add an #xpath method to Akephalos::Node so that calling #path on Akephalos::Capybara::Node doesn't blow up
|
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index fa98e01..dbc08af 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,156 +1,161 @@
module Akephalos
# Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
# interacting with an element on the page.
class Node
# @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
# @return [true, false] whether the element is checked
def checked?
@_node.isChecked
end
# @return [String] inner text of the node
def text
@_node.asText
end
# Return the value of the node's attribute.
#
# @param [String] name attribute on node
# @return [String] the value of the named attribute
# @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
# Return the value of a form element. If the element is a select box and
# has "multiple" declared as an attribute, then all selected options will
# be returned as an array.
#
# @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
@_node.selected_options.map { |option| option.text }
else
selected_option = @_node.selected_options.first
selected_option ? selected_option.text : nil
end
when "textarea"
@_node.getText
else
self[:value]
end
end
# Set the value of the form input.
#
# @param [String] value
def value=(value)
case tag_name
when "textarea"
@_node.setText("")
type(value)
when "input"
if file_input?
@_node.setValueAttribute(value)
else
@_node.setValueAttribute("")
type(value)
end
end
end
# Types each character into a text or input field.
#
# @param [String] value the string to type
def type(value)
value.each_char do |c|
@_node.type(c)
end
end
# @return [true, false] whether the node is a file input
def file_input?
tag_name == "input" && @_node.getAttribute("type") == "file"
end
# Select an option from a select box by its value.
#
# @return [true, false] whether the selection was successful
def select_option(option)
opt = @_node.getOptions.detect { |o| o.asText == option }
opt && opt.setSelected(true)
end
# Unselect an option from a select box by its value.
#
# @return [true, false] whether the unselection was successful
def unselect_option(option)
opt = @_node.getOptions.detect { |o| o.asText == option }
opt && opt.setSelected(false)
end
# Return the option elements for a select box.
#
# @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
# Return the selected option elements for a select box.
#
# @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
# Fire a JavaScript event on the current node. Note that you should not
# prefix event names with "on", so:
#
# link.fire_event('mousedown')
#
# @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
# @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
# @return [true, false] whether the node is visible to the user accounting
# for CSS.
def visible?
@_node.isDisplayed
end
# Click the node and then wait for any triggered JavaScript callbacks to
# fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
# Search for child nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
+
+ # @return [String] the XPath expression for this node
+ def xpath
+ @_node.getCanonicalXPath
+ end
end
end
|
bernerdschaefer/akephalos
|
ee250afef5a8be413365b5552521ed6b87e7c20e
|
Bumping RSpec and Capybara versions
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 37e9b78..9808155 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
- s.add_runtime_dependency "capybara", "~> 0.4.0"
+ s.add_runtime_dependency "capybara", ">= 0.4.0"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
- s.add_development_dependency "rspec", "~> 2.3.0"
+ s.add_development_dependency "rspec", ">= 2.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
51ddd3813348188e86c94b836aa946c31946f6e7
|
Add 'ku' to JRuby options. This make JRuby works in UTF-8 mode
|
diff --git a/bin/akephalos b/bin/akephalos
index 7d59a06..53f1bfd 100755
--- a/bin/akephalos
+++ b/bin/akephalos
@@ -1,87 +1,88 @@
#!/usr/bin/env ruby
# vim:set filetype=ruby:
require "pathname"
require "optparse"
options = { :interactive => false }
parser = OptionParser.new do |opts|
opts.banner = "Usage: akephalos [--interactive, --use-htmlunit-snapshot] | [--server] <port>"
opts.on("-s", "--server", "Run in server mode (default)")
opts.on("-i", "--interactive", "Run in interactive mode") { options[:interactive] = true }
opts.on("--use-htmlunit-snapshot", "Use the snapshot of htmlunit") { options[:use_htmlunit_snapshot] = true }
opts.on_tail("-h", "--help", "Show this message") { puts opts; exit }
end
parser.parse!
root = Pathname(__FILE__).expand_path.dirname.parent
lib = root + 'lib'
src = root + 'src'
case
when options[:use_htmlunit_snapshot]
require "fileutils"
FileUtils.mkdir_p("vendor/htmlunit")
Dir["vendor/htmlunit/*.jar"].each { |jar| File.unlink(jar) }
Dir.chdir("vendor") do
$stdout.print "Downloading latest snapshot... "
$stdout.flush
%x[curl -O http://build.canoo.com/htmlunit/artifacts/htmlunit-2.9-SNAPSHOT-with-dependencies.zip &> /dev/null]
puts "done"
$stdout.print "Extracting dependencies... "
$stdout.flush
%x[unzip -j -d htmlunit htmlunit-2.9-SNAPSHOT-with-dependencies.zip htmlunit-2.9-SNAPSHOT/lib htmlunit-2.9-SNAPSHOT/lib/* &> /dev/null]
puts "done"
File.unlink "htmlunit-2.9-SNAPSHOT-with-dependencies.zip"
end
$stdout.puts "="*40
$stdout.puts "The latest HtmlUnit snapshot has been extracted to vendor/htmlunit!"
when options[:interactive]
$:.unshift('vendor', lib, src)
require 'rubygems'
require 'akephalos'
require 'akephalos/console'
Akephalos::Console.start
else
unless port = ARGV[0]
puts parser.help
exit
end
if RUBY_PLATFORM == "java"
$:.unshift("vendor", lib, src)
require 'akephalos/server'
Akephalos::Server.start!(port)
else
require 'rubygems'
require 'jruby-jars'
jruby = JRubyJars.core_jar_path
jruby_stdlib = JRubyJars.stdlib_jar_path
java_args = [
"-Xmx128M",
"-cp", [JRubyJars.core_jar_path, JRubyJars.stdlib_jar_path].join(":"),
"org.jruby.Main"
]
- ruby_args = [
+ ruby_args = [
+ "-Ku",
"-I", "vendor:#{lib}:#{src}",
"-r", "akephalos/server",
"-e", "Akephalos::Server.start!(#{port.inspect})"
]
# Bundler sets ENV["RUBYOPT"] to automatically load bundler/setup.rb, but
# since the akephalos server doesn't have any gem dependencies and is
# always executed with the same context, we clear RUBYOPT before running
# exec.
ENV["RUBYOPT"] = ""
exec("java", *(java_args + ruby_args))
end
end
|
bernerdschaefer/akephalos
|
e61ec54cbd1b3c8b3aa081a86d9f919f25b4b608
|
Remove automatic cucumber loading, force manual require.
|
diff --git a/lib/akephalos.rb b/lib/akephalos.rb
index e68efaf..b8fc300 100644
--- a/lib/akephalos.rb
+++ b/lib/akephalos.rb
@@ -1,23 +1,19 @@
# **Akephalos** is a cross-platform Ruby interface for *HtmlUnit*, a headless
# browser for the Java platform.
#
# The only requirement is that a Java runtime is available.
#
require 'java' if RUBY_PLATFORM == 'java'
require 'pathname'
module Akephalos
BIN_DIR = Pathname(__FILE__).expand_path.dirname.parent + 'bin'
end
require 'akephalos/client'
require 'capybara'
require 'akephalos/capybara'
Capybara.register_driver :akephalos do |app|
Capybara::Driver::Akephalos.new(app)
end
-
-if Object.const_defined? :Cucumber
- require 'akephalos/cucumber'
-end
|
bernerdschaefer/akephalos
|
1ba8fe113f834da171263db160b4e50a91a2748b
|
Revert "Attempt to ensure cucumber is loaded"
|
diff --git a/lib/akephalos/cucumber.rb b/lib/akephalos/cucumber.rb
index 9d2c744..6507532 100644
--- a/lib/akephalos/cucumber.rb
+++ b/lib/akephalos/cucumber.rb
@@ -1,7 +1,6 @@
-require 'cucumber'
require 'capybara/cucumber'
Before('@akephalos') do
Capybara.current_driver = :akephalos
end
|
bernerdschaefer/akephalos
|
ed99c651c9cc52c653241bbabcbb62fd3fcf1cda
|
Attempt to ensure cucumber is loaded
|
diff --git a/lib/akephalos/cucumber.rb b/lib/akephalos/cucumber.rb
index 6507532..9d2c744 100644
--- a/lib/akephalos/cucumber.rb
+++ b/lib/akephalos/cucumber.rb
@@ -1,6 +1,7 @@
+require 'cucumber'
require 'capybara/cucumber'
Before('@akephalos') do
Capybara.current_driver = :akephalos
end
|
bernerdschaefer/akephalos
|
cd5aab30043f2ac5466fe00e0396e9ea9ae58a7d
|
Add Node#file_input? back. Passes 29 additional tests.
|
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index 74e970e..38108d9 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,147 +1,153 @@
module Akephalos
# Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
# interacting with an element on the page.
class Node
# @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
# @return [true, false] whether the element is checked
def checked?
@_node.isChecked
end
# @return [String] inner text of the node
def text
@_node.asText
end
# Return the value of the node's attribute.
#
# @param [String] name attribute on node
# @return [String] the value of the named attribute
# @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
# Return the value of a form element. If the element is a select box and
# has "multiple" declared as an attribute, then all selected options will
# be returned as an array.
#
# @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
selected_options.map { |option| option.value }
else
selected_option = @_node.selected_options.first
selected_option ? Node.new(selected_option).value : nil
end
when "option"
self[:value] || text
when "textarea"
@_node.getText
else
self[:value]
end
end
# Set the value of the form input.
#
# @param [String] value
def value=(value)
case tag_name
when "textarea"
@_node.setText("")
type(value)
when "input"
if file_input?
@_node.setValueAttribute(value)
else
@_node.setValueAttribute("")
type(value)
end
end
end
# Types each character into a text or input field.
#
# @param [String] value the string to type
def type(value)
value.each_char do |c|
@_node.type(c)
end
end
# @return [true, false] whether the node allows multiple-option selection (if the node is a select).
def multiple_select?
!self[:multiple].nil?
end
+ # @return [true, false] whether the node is a file input
+ def file_input?
+ tag_name == "input" && @_node.getAttribute("type") == "file"
+ end
+
+
# Unselect an option.
#
# @return [true, false] whether the unselection was successful
def unselect
@_node.setSelected(false)
end
# Return the option elements for a select box.
#
# @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
# Return the selected option elements for a select box.
#
# @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
# Fire a JavaScript event on the current node. Note that you should not
# prefix event names with "on", so:
#
# link.fire_event('mousedown')
#
# @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
# @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
# @return [true, false] whether the node is visible to the user accounting
# for CSS.
def visible?
@_node.isDisplayed
end
# Click the node and then wait for any triggered JavaScript callbacks to
# fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
# Search for child nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
end
end
|
bernerdschaefer/akephalos
|
4d4530ea23572d9aaf7cb1852adaaf24f4643960
|
Register akephalos as a driver.
|
diff --git a/lib/akephalos.rb b/lib/akephalos.rb
index 4f77a8a..e68efaf 100644
--- a/lib/akephalos.rb
+++ b/lib/akephalos.rb
@@ -1,19 +1,23 @@
# **Akephalos** is a cross-platform Ruby interface for *HtmlUnit*, a headless
# browser for the Java platform.
#
# The only requirement is that a Java runtime is available.
#
require 'java' if RUBY_PLATFORM == 'java'
require 'pathname'
module Akephalos
BIN_DIR = Pathname(__FILE__).expand_path.dirname.parent + 'bin'
end
require 'akephalos/client'
require 'capybara'
require 'akephalos/capybara'
+Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app)
+end
+
if Object.const_defined? :Cucumber
require 'akephalos/cucumber'
end
|
bernerdschaefer/akephalos
|
0cde86e40f4f335c53b03fecdb14eba702f43289
|
Nudge rspec requirement to 2.3.0
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 1e6522e..37e9b78 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
s.add_runtime_dependency "capybara", "~> 0.4.0"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
- s.add_development_dependency "rspec", "1.3.0"
+ s.add_development_dependency "rspec", "~> 2.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
4e429455fa9999e3bb38927a996dcab166987049
|
Got way ahead of ourselves there. Minor, not major.
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 4125c4f..1e6522e 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
- s.add_runtime_dependency "capybara", "~> 4.0.0"
+ s.add_runtime_dependency "capybara", "~> 0.4.0"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
s.add_development_dependency "rspec", "1.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
e58945191aa9ad169e0147ff09692331018828d6
|
Bump capybara dependency to make it play nice with cucumber/evergreen stack
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 9d41cd7..4125c4f 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
- s.add_runtime_dependency "capybara", "~> 0.3.8"
+ s.add_runtime_dependency "capybara", "~> 4.0.0"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
s.add_development_dependency "rspec", "1.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
bbc67f2096ecee71b16c38a9de48bd40f6e7b540
|
Relax Capybara version dependency
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 9d41cd7..b0e5fe0 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
- s.add_runtime_dependency "capybara", "~> 0.3.8"
+ s.add_runtime_dependency "capybara", "~> 0.3"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
s.add_development_dependency "rspec", "1.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
cece93c3d09cd843abf99f87360763dca4251749
|
fixed cookie should include domain spec
|
diff --git a/spec/integration/cookies_spec.rb b/spec/integration/cookies_spec.rb
index 311c481..4e0fb39 100644
--- a/spec/integration/cookies_spec.rb
+++ b/spec/integration/cookies_spec.rb
@@ -1,91 +1,91 @@
require 'spec_helper'
describe Capybara::Driver::Akephalos do
context 'with akephalos driver' do
let(:driver) { Capybara::Driver::Akephalos.new(Application) }
after { driver.reset! }
describe "#cookies" do
context "when no cookies are set" do
it "returns an empty array" do
driver.cookies.should be_empty
end
end
context "when cookies are set" do
before { driver.visit("/set_cookie") }
it "returns the cookies" do
driver.cookies.should_not be_empty
end
describe "#cookies.each" do
it "yields cookie objects" do
yielded = false
driver.cookies.each { yielded = true }
yielded.should be_true
end
end
describe "#cleanup!" do
it "clears the cookies" do
driver.cleanup!
driver.cookies.should be_empty
end
end
describe "#cookies.delete" do
it "removes the cookie from the sesison" do
driver.cookies.delete(driver.cookies["capybara"])
driver.cookies.should be_empty
end
end
describe "#cookies[]" do
context "when the cookie exists" do
it "returns the named cookie" do
driver.cookies["capybara"].should_not be_nil
end
context "the cookie" do
let(:cookie) { driver.cookies["capybara"] }
it "includes the name" do
cookie.name.should == "capybara"
end
it "includes the domain" do
- cookie.domain.should == "localhost"
+ ["localhost", "127.0.0.1", "0.0.0.0"].include?(cookie.domain).should be_true
end
it "includes the path" do
cookie.path.should == "/"
end
it "includes the value" do
cookie.value.should == "test_cookie"
end
it "includes the expiration" do
cookie.expires.should be_nil
end
it "includes security" do
cookie.should_not be_secure
end
end
end
context "when the cookie does not exist" do
it "returns nil" do
driver.cookies["nonexistant"].should be_nil
end
end
end
end
end
end
end
|
bernerdschaefer/akephalos
|
6299d243c7a8a779ce30d017fba92efc9163d674
|
gitingore for rubymine
|
diff --git a/.gitignore b/.gitignore
index 9f80dbc..776c7fb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,10 @@
.bundle/
.rvmrc
.yardoc
Gemfile.lock
burn
docs/build
pkg
tags
+
+.idea/
|
bernerdschaefer/akephalos
|
e8df49fa5c6e656067f7f991b5d4c8e88a191cfe
|
Type into form fields to allow JS keyboard events
|
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index fb2a413..fa98e01 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,136 +1,156 @@
module Akephalos
# Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
# interacting with an element on the page.
class Node
# @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
# @return [true, false] whether the element is checked
def checked?
@_node.isChecked
end
# @return [String] inner text of the node
def text
@_node.asText
end
# Return the value of the node's attribute.
#
# @param [String] name attribute on node
# @return [String] the value of the named attribute
# @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
# Return the value of a form element. If the element is a select box and
# has "multiple" declared as an attribute, then all selected options will
# be returned as an array.
#
# @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
@_node.selected_options.map { |option| option.text }
else
selected_option = @_node.selected_options.first
selected_option ? selected_option.text : nil
end
when "textarea"
@_node.getText
else
self[:value]
end
end
# Set the value of the form input.
#
# @param [String] value
def value=(value)
case tag_name
when "textarea"
- @_node.setText(value)
+ @_node.setText("")
+ type(value)
when "input"
- @_node.setValueAttribute(value)
+ if file_input?
+ @_node.setValueAttribute(value)
+ else
+ @_node.setValueAttribute("")
+ type(value)
+ end
+ end
+ end
+
+ # Types each character into a text or input field.
+ #
+ # @param [String] value the string to type
+ def type(value)
+ value.each_char do |c|
+ @_node.type(c)
end
end
+ # @return [true, false] whether the node is a file input
+ def file_input?
+ tag_name == "input" && @_node.getAttribute("type") == "file"
+ end
+
# Select an option from a select box by its value.
#
# @return [true, false] whether the selection was successful
def select_option(option)
opt = @_node.getOptions.detect { |o| o.asText == option }
opt && opt.setSelected(true)
end
# Unselect an option from a select box by its value.
#
# @return [true, false] whether the unselection was successful
def unselect_option(option)
opt = @_node.getOptions.detect { |o| o.asText == option }
opt && opt.setSelected(false)
end
# Return the option elements for a select box.
#
# @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
# Return the selected option elements for a select box.
#
# @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
# Fire a JavaScript event on the current node. Note that you should not
# prefix event names with "on", so:
#
# link.fire_event('mousedown')
#
# @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
# @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
# @return [true, false] whether the node is visible to the user accounting
# for CSS.
def visible?
@_node.isDisplayed
end
# Click the node and then wait for any triggered JavaScript callbacks to
# fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
# Search for child nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
end
end
|
bernerdschaefer/akephalos
|
40674ad2cc3c1eedc8b98cbac000adaa04d27efd
|
Initial work to migrate to Capybara 0.4. Six outstanding spec failures: 3 seem like overly-restrictive tests within the Capybara conformance suite, 2 are related to drag-and-drop and may have been false positives before, and the other seems like a genuine problem.
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 7889d19..e38b52d 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,280 +1,293 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
- # Akephalos-specific implementation for Capybara's Node class.
- class Node < Capybara::Node
+ # Akephalos-specific implementation for Capybara's Driver::Node class.
+ class Node < Capybara::Driver::Node
+
+ # @api capybara
+ # @return [String] the inner text of the node
+ def text
+ native.text
+ end
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
- node.checked?
+ native.checked?
else
- node[name.to_s]
+ native[name.to_s]
end
end
# @api capybara
- # @return [String] the inner text of the node
- def text
- node.text
- end
-
- # @api capybara
- # @return [String] the form element's value
+ # @return [String, Array<String>] the form element's value
def value
- node.value
+ native.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
- node.value = value.to_s
+ native.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
- node.value = value.to_s
+ native.value = value.to_s
end
end
- # Select an option from a select box.
- #
# @api capybara
- # @param [String] option the option to select
- def select(option)
- result = node.select_option(option)
-
- if result == nil
- options = node.options.map(&:text).join(", ")
- raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
- else
- result
- end
+ def select_option
+ native.click
end
# Unselect an option from a select box.
#
# @api capybara
- # @param [String] option the option to unselect
- def unselect(option)
- unless self[:multiple]
- raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
+ def unselect_option
+ unless select_node.multiple_select?
+ raise Capybara::UnselectNotAllowed, "Cannot unselect option from single select box."
end
- result = node.unselect_option(option)
+ native.unselect
+ end
- if result == nil
- options = node.options.map(&:text).join(", ")
- raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
- else
- result
- end
+ # Click the element.
+ def click
+ native.click
end
- # Trigger an event on the element.
+ # Drag the element on top of the target element.
#
# @api capybara
- # @param [String] event the event to trigger
- def trigger(event)
- node.fire_event(event.to_s)
+ # @param [Node] element the target element
+ def drag_to(element)
+ trigger('mousedown')
+ element.trigger('mousemove')
+ element.trigger('mouseup')
end
# @api capybara
# @return [String] the element's tag name
def tag_name
- node.tag_name
+ native.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
- node.visible?
+ native.visible?
end
- # Drag the element on top of the target element.
+ # @api capybara
+ # @return [String] the XPath to locate the node
+ def path
+ native.xpath
+ end
+
+ # Trigger an event on the element.
#
# @api capybara
- # @param [Node] element the target element
- def drag_to(element)
- trigger('mousedown')
- element.trigger('mousemove')
- element.trigger('mouseup')
+ # @param [String] event the event to trigger
+ def trigger(event)
+ native.fire_event(event.to_s)
end
- # Click the element.
- def click
- node.click
+ # @api capybara
+ # @param [String] selector XPath query
+ # @return [Array<Node>] the matched nodes
+ def find(selector)
+ nodes = []
+ native.find(selector).each { |node| nodes << self.class.new(self, node) }
+ nodes
+ end
+
+ protected
+
+ # @return [true, false] whether the node allows multiple-option selection (if the node is a select).
+ def multiple_select?
+ tag_name == "select" && native.multiple_select?
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
- node.find(selector).each { |node| nodes << Node.new(driver, node) }
+ native.find(selector).each { |node| nodes << self.class.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
- node[:type]
+ native[:type]
+ end
+
+ # @return [Node] the select node, if this is an option node
+ def select_node
+ find('./ancestor::select').first
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
# {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# @return the session cookies
def cookies
browser.cookies
end
# @return [String] the current user agent string
def user_agent
browser.user_agent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
browser.user_agent = user_agent
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
+
+Capybara.register_driver :akephalos do |app|
+ Capybara::Driver::Akephalos.new(app)
+end
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index fb2a413..81a78f6 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,136 +1,132 @@
module Akephalos
# Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
# interacting with an element on the page.
class Node
# @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
# @return [true, false] whether the element is checked
def checked?
@_node.isChecked
end
# @return [String] inner text of the node
def text
@_node.asText
end
# Return the value of the node's attribute.
#
# @param [String] name attribute on node
# @return [String] the value of the named attribute
# @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
# Return the value of a form element. If the element is a select box and
# has "multiple" declared as an attribute, then all selected options will
# be returned as an array.
#
# @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
- @_node.selected_options.map { |option| option.text }
+ selected_options.map { |option| option.value }
else
selected_option = @_node.selected_options.first
- selected_option ? selected_option.text : nil
+ selected_option ? Node.new(selected_option).value : nil
end
+ when "option"
+ self[:value] || text
when "textarea"
@_node.getText
else
self[:value]
end
end
# Set the value of the form input.
#
# @param [String] value
def value=(value)
case tag_name
when "textarea"
@_node.setText(value)
when "input"
@_node.setValueAttribute(value)
end
end
- # Select an option from a select box by its value.
- #
- # @return [true, false] whether the selection was successful
- def select_option(option)
- opt = @_node.getOptions.detect { |o| o.asText == option }
-
- opt && opt.setSelected(true)
+ # @return [true, false] whether the node allows multiple-option selection (if the node is a select).
+ def multiple_select?
+ !self[:multiple].nil?
end
- # Unselect an option from a select box by its value.
+ # Unselect an option.
#
# @return [true, false] whether the unselection was successful
- def unselect_option(option)
- opt = @_node.getOptions.detect { |o| o.asText == option }
-
- opt && opt.setSelected(false)
+ def unselect
+ @_node.setSelected(false)
end
# Return the option elements for a select box.
#
# @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
# Return the selected option elements for a select box.
#
# @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
# Fire a JavaScript event on the current node. Note that you should not
# prefix event names with "on", so:
#
# link.fire_event('mousedown')
#
# @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
# @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
# @return [true, false] whether the node is visible to the user accounting
# for CSS.
def visible?
@_node.isDisplayed
end
# Click the node and then wait for any triggered JavaScript callbacks to
# fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
# Search for child nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
end
end
|
bernerdschaefer/akephalos
|
6b3f368a001a80b576cd7e872607943adb14033d
|
Migrating to Capybara 0.4: updated Capybara and RSpec dependencies in Gemspec; moved spec/spec.opts to .rpsec; Explicitly add the current directory to the search path for Ruby 1.9
|
diff --git a/spec/spec.opts b/.rspec
similarity index 100%
rename from spec/spec.opts
rename to .rspec
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 9d41cd7..f6fb5be 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
- s.add_runtime_dependency "capybara", "~> 0.3.8"
+ s.add_runtime_dependency "capybara", "~> 0.4.0"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
- s.add_development_dependency "rspec", "1.3.0"
+ s.add_development_dependency "rspec", "~> 2.1.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_paths = %w(lib src)
s.executables = %w(akephalos)
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 028bd00..e067dfe 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,20 +1,20 @@
require 'rubygems'
root = File.expand_path('../../', __FILE__)
-%w(vendor lib src).each do |dir|
- dir = File.join(root, dir)
+lib_paths = [root] + %w(vendor lib src).collect { |dir| File.join(root, dir) }
+(lib_paths).each do |dir|
$:.unshift dir unless $:.include?(dir)
end
require 'akephalos'
spec_dir = nil
$:.detect do |dir|
if File.exists? File.join(dir, "capybara.rb")
spec_dir = File.expand_path(File.join(dir,"..","spec"))
$:.unshift( spec_dir )
end
end
require File.join(spec_dir,"spec_helper")
require "spec/support/application"
|
bernerdschaefer/akephalos
|
63d0541b7f4368ecd754ea087f13c1058008b5c6
|
Try being explicit with DRb hosts and ports
|
diff --git a/lib/akephalos/remote_client.rb b/lib/akephalos/remote_client.rb
index 798805d..1fbc94b 100644
--- a/lib/akephalos/remote_client.rb
+++ b/lib/akephalos/remote_client.rb
@@ -1,84 +1,84 @@
require 'socket'
require 'drb/drb'
# We need to define our own NativeException class for the cases when a native
# exception is raised by the JRuby DRb server.
class NativeException < StandardError; end
module Akephalos
# The +RemoteClient+ class provides an interface to an +Akephalos::Client+
# isntance on a remote DRb server.
#
# == Usage
# client = Akephalos::RemoteClient.new
# client.visit "http://www.oinopa.com"
# client.page.source # => "<!DOCTYPE html PUBLIC..."
class RemoteClient
# Start a remote akephalos server and return the remote Akephalos::Client
# instance.
#
# @return [DRbObject] the remote client instance
def self.new
server_port = start!
- DRb.start_service
+ DRb.start_service("druby://127.0.0.1:#{find_available_port}")
client = DRbObject.new_with_uri("druby://127.0.0.1:#{server_port}")
# We want to share our local configuration with the remote server
# process, so we share an undumped version of our configuration. This
# lets us continue to make changes locally and have them reflected in the
# remote process.
client.configuration = Akephalos.configuration.extend(DRbUndumped)
client
end
# Start a remote server process and return when it is available for use.
def self.start!
port = find_available_port
remote_client = IO.popen("#{Akephalos::BIN_DIR + 'akephalos'} #{port}")
# Set up a monitor thread to detect if the forked server exits
# prematurely.
server_monitor = Thread.new { Thread.current[:exited] = Process.wait(remote_client.pid) }
# Wait for the server to be accessible on the socket we specified.
until responsive?(port)
exit!(1) if server_monitor[:exited]
sleep 0.5
end
server_monitor.kill
# Ensure that the remote server shuts down gracefully when we are
# finished.
at_exit { Process.kill(:INT, remote_client.pid) }
port
end
private
# @api private
# @param [Integer] port the port to check for responsiveness
# @return [true, false] whether the port is responsive
def self.responsive?(port)
- socket = TCPSocket.open("127.0.0.1", port)
+ socket = TCPSocket.open('127.0.0.1', port)
true
rescue Errno::ECONNREFUSED
false
ensure
socket.close if socket
end
# @api private
# @return [Integer] the next available port
def self.find_available_port
server = TCPServer.new('127.0.0.1', 0)
server.addr[1]
ensure
server.close if server
end
end
end
|
bernerdschaefer/akephalos
|
017482a913801af32020a8ae929340fcb77974bc
|
Add integration test for changing app_host
|
diff --git a/spec/integration/subdomains_spec.rb b/spec/integration/subdomains_spec.rb
new file mode 100644
index 0000000..d1e17ac
--- /dev/null
+++ b/spec/integration/subdomains_spec.rb
@@ -0,0 +1,42 @@
+require 'spec_helper'
+
+describe Capybara::Driver::Akephalos do
+
+ let(:driver) { Capybara::Driver::Akephalos.new(Application) }
+ after do
+ Capybara.app_host = nil
+ driver.reset!
+ end
+
+ context "when changing Capybara.app_host" do
+ it "defaults app_host settings" do
+ url = driver.rack_server.url("/app_domain_detection")
+ driver.visit "/app_domain_detection"
+ driver.body.should include(url)
+ driver.current_url.should == url
+ end
+
+ it "respects the app_host setting" do
+ url = "http://smackaho.st:#{driver.rack_server.port}/app_domain_detection"
+ Capybara.app_host = "http://smackaho.st:#{driver.rack_server.port}"
+ driver.visit "/app_domain_detection"
+ driver.body.should include(url)
+ driver.current_url.should == url
+ end
+
+ it "allows changing app_host multiple times" do
+ url = "http://sub1.smackaho.st:#{driver.rack_server.port}/app_domain_detection"
+ Capybara.app_host = "http://sub1.smackaho.st:#{driver.rack_server.port}"
+ driver.visit "/app_domain_detection"
+ driver.body.should include(url)
+ driver.current_url.should == url
+
+ url = "http://sub2.smackaho.st:#{driver.rack_server.port}/app_domain_detection"
+ Capybara.app_host = "http://sub2.smackaho.st:#{driver.rack_server.port}"
+ driver.visit "/app_domain_detection"
+ driver.body.should include(url)
+ driver.current_url.should == url
+ end
+ end
+
+end
diff --git a/spec/support/application.rb b/spec/support/application.rb
index 93f5ac8..452f065 100644
--- a/spec/support/application.rb
+++ b/spec/support/application.rb
@@ -1,36 +1,40 @@
class Application < TestApp
get '/slow_page' do
sleep 1
"<p>Loaded!</p>"
end
get '/slow_ajax_load' do
<<-HTML
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>with_js</title>
<script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$('#ajax_load').click(function() {
$('body').load('/slow_page');
return false;
});
});
</script>
</head>
<body>
<a href="#" id="ajax_load">Click me</a>
</body>
HTML
end
get '/user_agent_detection' do
request.user_agent
end
+
+ get '/app_domain_detection' do
+ "http://#{request.host_with_port}/app_domain_detection"
+ end
end
if $0 == __FILE__
Rack::Handler::Mongrel.run Application, :Port => 8070
end
|
bernerdschaefer/akephalos
|
8e1347a5a5da688ccf3f393b05ee15f410ebc7e2
|
Documentation formatting fix
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index be25836..7889d19 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,280 +1,280 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
- # {#reset!} instead.
+ # {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# @return the session cookies
def cookies
browser.cookies
end
# @return [String] the current user agent string
def user_agent
browser.user_agent
end
# Set the User-Agent header for this session. If :default is given, the
# User-Agent header will be reset to the default browser's user agent.
#
# @param [:default] user_agent the default user agent
# @param [String] user_agent the user agent string to use
def user_agent=(user_agent)
browser.user_agent = user_agent
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
|
bernerdschaefer/akephalos
|
2c4e6fe96d394e58947c0e5f1de88f93d8ece08a
|
Add user_agent API methods to driver
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 8d4642d..be25836 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,266 +1,280 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
# @deprecated This method is deprecated in Capybara's master branch. Use
# {#reset!} instead.
def cleanup!
reset!
end
# Clear all cookie session data.
def reset!
cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# @return the session cookies
def cookies
browser.cookies
end
+ # @return [String] the current user agent string
+ def user_agent
+ browser.user_agent
+ end
+
+ # Set the User-Agent header for this session. If :default is given, the
+ # User-Agent header will be reset to the default browser's user agent.
+ #
+ # @param [:default] user_agent the default user agent
+ # @param [String] user_agent the user agent string to use
+ def user_agent=(user_agent)
+ browser.user_agent = user_agent
+ end
+
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index a7304df..aeef0ec 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,91 +1,111 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = HtmlUnit::WebClient.new
Filter.new(client)
client.setAjaxController(HtmlUnit::NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(HtmlUnit::SilentCssErrorHandler.new)
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
# @return [Cookies] the cookies for this session
def cookies
@cookies ||= Cookies.new(client.getCookieManager)
end
+ # @return [String] the current user agent string
+ def user_agent
+ @user_agent || client.getBrowserVersion.getUserAgent
+ end
+
+ # Set the User-Agent header for this session. If :default is given, the
+ # User-Agent header will be reset to the default browser's user agent.
+ #
+ # @param [:default] user_agent the default user agent
+ # @param [String] user_agent the user agent string to use
+ def user_agent=(user_agent)
+ if user_agent == :default
+ @user_agent = nil
+ client.removeRequestHeader("User-Agent")
+ else
+ @user_agent = user_agent
+ client.addRequestHeader("User-Agent", user_agent)
+ end
+ end
+
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/spec/integration/user_agent_spec.rb b/spec/integration/user_agent_spec.rb
new file mode 100644
index 0000000..70a6293
--- /dev/null
+++ b/spec/integration/user_agent_spec.rb
@@ -0,0 +1,63 @@
+require 'spec_helper'
+
+describe Capybara::Driver::Akephalos do
+
+ let(:driver) { Capybara::Driver::Akephalos.new(Application) }
+ after do
+ driver.user_agent = :default
+ driver.reset!
+ end
+
+ describe "#user_agent=" do
+ context "when given :default" do
+ it "resets the user agent" do
+ driver.user_agent = "something else"
+ driver.user_agent = :default
+ driver.user_agent.should =~ /Firefox/
+ end
+ end
+
+ context "when given a string" do
+ it "sets the user agent" do
+ new_user_agent = "iPhone user agent"
+ driver.user_agent = new_user_agent
+ driver.user_agent.should == new_user_agent
+ end
+ end
+ end
+
+ describe "#user_agent" do
+ context "with the default set" do
+ it "returns the default user agent string" do
+ driver.user_agent.should =~ /Firefox/
+ end
+ end
+ end
+
+ context "when requesting a page" do
+ context "with no user agent set" do
+ it "sends the default header" do
+ driver.visit "/user_agent_detection"
+ driver.body.should include("Firefox")
+ end
+ end
+
+ context "with a user agent set" do
+ it "sends the given user agent header" do
+ driver.user_agent = "iPhone user agent"
+ driver.visit "/user_agent_detection"
+ driver.body.should include("iPhone user agent")
+ end
+
+ context "when resetting back to default" do
+ it "sends the default user agent header" do
+ driver.user_agent = :default
+ driver.visit "/user_agent_detection"
+ driver.body.should include("Firefox")
+ end
+ end
+ end
+
+ end
+
+end
diff --git a/spec/support/application.rb b/spec/support/application.rb
index ec285b9..93f5ac8 100644
--- a/spec/support/application.rb
+++ b/spec/support/application.rb
@@ -1,32 +1,36 @@
class Application < TestApp
get '/slow_page' do
sleep 1
"<p>Loaded!</p>"
end
get '/slow_ajax_load' do
<<-HTML
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>with_js</title>
<script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$('#ajax_load').click(function() {
$('body').load('/slow_page');
return false;
});
});
</script>
</head>
<body>
<a href="#" id="ajax_load">Click me</a>
</body>
HTML
end
+
+ get '/user_agent_detection' do
+ request.user_agent
+ end
end
if $0 == __FILE__
Rack::Handler::Mongrel.run Application, :Port => 8070
end
|
bernerdschaefer/akephalos
|
cd9dc8ad82fd10411a6060c2ae014859974d1cf2
|
Add rubygems source to Gemfile
|
diff --git a/Gemfile b/Gemfile
index e0a7662..e45e65f 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1 +1,2 @@
+source :rubygems
gemspec
|
bernerdschaefer/akephalos
|
43af5866c7a138431b075a2321e6e09f6a47972a
|
Isolate HtmlUnit classes in HtmlUnit namespace
|
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index 9a5b4a1..a7304df 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,94 +1,91 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
- java_import 'com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController'
- java_import 'com.gargoylesoftware.htmlunit.SilentCssErrorHandler'
-
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
- client = WebClient.new
+ client = HtmlUnit::WebClient.new
Filter.new(client)
- client.setAjaxController(NicelyResynchronizingAjaxController.new)
- client.setCssErrorHandler(SilentCssErrorHandler.new)
+ client.setAjaxController(HtmlUnit::NicelyResynchronizingAjaxController.new)
+ client.setCssErrorHandler(HtmlUnit::SilentCssErrorHandler.new)
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
# @return [Cookies] the cookies for this session
def cookies
@cookies ||= Cookies.new(client.getCookieManager)
end
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/lib/akephalos/client/filter.rb b/lib/akephalos/client/filter.rb
index 0c86fc9..ff21815 100644
--- a/lib/akephalos/client/filter.rb
+++ b/lib/akephalos/client/filter.rb
@@ -1,122 +1,120 @@
module Akephalos
class Client
# Akephalos::Client::Filter extends HtmlUnit's WebConnectionWrapper to
# enable filtering outgoing requests generated interally by HtmlUnit.
#
# When a request comes through, it will be tested against the filters
# defined in Akephalos.filters and return a mock response if a match is
# found. If no filters are defined, or no filters match the request, then
# the response will bubble up to HtmlUnit for the normal request/response
# cycle.
- class Filter < WebConnectionWrapper
- java_import 'com.gargoylesoftware.htmlunit.util.NameValuePair'
- java_import 'com.gargoylesoftware.htmlunit.WebResponseData'
- java_import 'com.gargoylesoftware.htmlunit.WebResponseImpl'
-
+ class Filter < HtmlUnit::Util::WebConnectionWrapper
# Filters an outgoing request, and if a match is found, returns the mock
# response.
#
# @param [WebRequest] request the pending HTTP request
# @return [WebResponseImpl] when the request matches a defined filter
# @return [nil] when no filters match the request
def filter(request)
if filter = find_filter(request)
start_time = Time.now
- headers = filter[:headers].map { |name, value| NameValuePair.new(name.to_s, value.to_s) }
- response = WebResponseData.new(
+ headers = filter[:headers].map do |name, value|
+ HtmlUnit::Util::NameValuePair.new(name.to_s, value.to_s)
+ end
+ response = HtmlUnit::WebResponseData.new(
filter[:body].to_s.to_java_bytes,
filter[:status],
HTTP_STATUS_CODES.fetch(filter[:status], "Unknown"),
headers
)
- WebResponseImpl.new(response, request, Time.now - start_time)
+ HtmlUnit::WebResponseImpl.new(response, request, Time.now - start_time)
end
end
# Searches for a filter which matches the request's HTTP method and url.
#
# @param [WebRequest] request the pending HTTP request
# @return [Hash] when a filter matches the request
# @return [nil] when no filters match the request
def find_filter(request)
Akephalos.filters.find do |filter|
request.http_method === filter[:method] && request.url.to_s =~ filter[:filter]
end
end
# This method is called by WebClient when a page is requested, and will
# return a mock response if the request matches a defined filter or else
# return the actual response.
#
# @api htmlunit
# @param [WebRequest] request the pending HTTP request
# @return [WebResponseImpl]
def getResponse(request)
filter(request) || super
end
# Map of status codes to their English descriptions.
HTTP_STATUS_CODES = {
100 => "Continue",
101 => "Switching Protocols",
102 => "Processing",
200 => "OK",
201 => "Created",
202 => "Accepted",
203 => "Non-Authoritative Information",
204 => "No Content",
205 => "Reset Content",
206 => "Partial Content",
207 => "Multi-Status",
300 => "Multiple Choices",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
305 => "Use Proxy",
306 => "Switch Proxy",
307 => "Temporary Redirect",
400 => "Bad Request",
401 => "Unauthorized",
402 => "Payment Required",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
406 => "Not Acceptable",
407 => "Proxy Authentication Required",
408 => "Request Timeout",
409 => "Conflict",
410 => "Gone",
411 => "Length Required",
412 => "Precondition Failed",
413 => "Request Entity Too Large",
414 => "Request-URI Too Long",
415 => "Unsupported Media Type",
416 => "Requested Range Not Satisfiable",
417 => "Expectation Failed",
418 => "I'm a teapot",
421 => "There are too many connections from your internet address",
422 => "Unprocessable Entity",
423 => "Locked",
424 => "Failed Dependency",
425 => "Unordered Collection",
426 => "Upgrade Required",
449 => "Retry With",
450 => "Blocked by Windows Parental Controls",
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
505 => "HTTP Version Not Supported",
506 => "Variant Also Negotiates",
507 => "Insufficient Storage",
509 => "Bandwidth Limit Exceeded",
510 => "Not Extended",
530 => "User access denied"
}.freeze
end
end
end
diff --git a/lib/akephalos/htmlunit.rb b/lib/akephalos/htmlunit.rb
index 4fe1520..072b142 100644
--- a/lib/akephalos/htmlunit.rb
+++ b/lib/akephalos/htmlunit.rb
@@ -1,27 +1,38 @@
require "pathname"
require "java"
dependency_directory = $:.detect { |path| Dir[File.join(path, 'htmlunit/htmlunit-*.jar')].any? }
raise "Could not find htmlunit/htmlunit-VERSION.jar in load path:\n [ #{$:.join(",\n ")}\n ]" unless dependency_directory
Dir[File.join(dependency_directory, "htmlunit/*.jar")].each do |jar|
require jar
end
java.lang.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog")
java.lang.System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "fatal")
java.lang.System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true")
-java_import "com.gargoylesoftware.htmlunit.WebClient"
-java_import "com.gargoylesoftware.htmlunit.util.WebConnectionWrapper"
-java_import 'com.gargoylesoftware.htmlunit.HttpMethod'
-
-
-# Disable history tracking
-com.gargoylesoftware.htmlunit.History.field_reader :ignoreNewPages_
-
-# Run in Firefox compatibility mode
-com.gargoylesoftware.htmlunit.BrowserVersion.setDefault(
- com.gargoylesoftware.htmlunit.BrowserVersion::FIREFOX_3
-)
+# Container module for com.gargoylesoftware.htmlunit namespace.
+module HtmlUnit
+ java_import "com.gargoylesoftware.htmlunit.BrowserVersion"
+ java_import "com.gargoylesoftware.htmlunit.History"
+ java_import "com.gargoylesoftware.htmlunit.HttpMethod"
+ java_import "com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController"
+ java_import "com.gargoylesoftware.htmlunit.SilentCssErrorHandler"
+ java_import "com.gargoylesoftware.htmlunit.WebClient"
+ java_import "com.gargoylesoftware.htmlunit.WebResponseData"
+ java_import "com.gargoylesoftware.htmlunit.WebResponseImpl"
+
+ # Container module for com.gargoylesoftware.htmlunit.util namespace.
+ module Util
+ java_import "com.gargoylesoftware.htmlunit.util.NameValuePair"
+ java_import "com.gargoylesoftware.htmlunit.util.WebConnectionWrapper"
+ end
+
+ # Disable history tracking
+ History.field_reader :ignoreNewPages_
+
+ # Run in Firefox compatibility mode
+ BrowserVersion.setDefault(BrowserVersion::FIREFOX_3)
+end
diff --git a/lib/akephalos/htmlunit/ext/http_method.rb b/lib/akephalos/htmlunit/ext/http_method.rb
index 610ef42..e21baad 100644
--- a/lib/akephalos/htmlunit/ext/http_method.rb
+++ b/lib/akephalos/htmlunit/ext/http_method.rb
@@ -1,28 +1,30 @@
-# Reopen com.gargoylesoftware.htmlunit.HttpMethod to add convenience methods.
-class HttpMethod
+module HtmlUnit
+ # Reopen HtmlUnit's HttpMethod class to add convenience methods.
+ class HttpMethod
- # Loosely compare HttpMethod with another object, accepting either an
- # HttpMethod instance or a symbol describing the method. Note that :any is a
- # special symbol which will always return true.
- #
- # @param [HttpMethod] other an HtmlUnit HttpMethod object
- # @param [Symbol] other a symbolized representation of an http method
- # @return [true/false]
- def ===(other)
- case other
- when HttpMethod
- super
- when :any
- true
- when :get
- self == self.class::GET
- when :post
- self == self.class::POST
- when :put
- self == self.class::PUT
- when :delete
- self == self.class::DELETE
+ # Loosely compare HttpMethod with another object, accepting either an
+ # HttpMethod instance or a symbol describing the method. Note that :any is a
+ # special symbol which will always return true.
+ #
+ # @param [HttpMethod] other an HtmlUnit HttpMethod object
+ # @param [Symbol] other a symbolized representation of an http method
+ # @return [true/false]
+ def ===(other)
+ case other
+ when HttpMethod
+ super
+ when :any
+ true
+ when :get
+ self == self.class::GET
+ when :post
+ self == self.class::POST
+ when :put
+ self == self.class::PUT
+ when :delete
+ self == self.class::DELETE
+ end
end
- end
+ end
end
|
bernerdschaefer/akephalos
|
bbeb72836daca2dead3f7614ab62cd26446bdaeb
|
Use TCP Sockets instead of Unix Domain Sockets
|
diff --git a/bin/akephalos b/bin/akephalos
index 89f65db..c43ea0f 100755
--- a/bin/akephalos
+++ b/bin/akephalos
@@ -1,87 +1,87 @@
#!/usr/bin/env ruby
# vim:set filetype=ruby:
require "pathname"
require "optparse"
options = { :interactive => false }
parser = OptionParser.new do |opts|
- opts.banner = "Usage: akephalos [--interactive, --use-htmlunit-snapshot] | [--server] <socket_file>"
+ opts.banner = "Usage: akephalos [--interactive, --use-htmlunit-snapshot] | [--server] <port>"
opts.on("-s", "--server", "Run in server mode (default)")
opts.on("-i", "--interactive", "Run in interactive mode") { options[:interactive] = true }
opts.on("--use-htmlunit-snapshot", "Use the snapshot of htmlunit") { options[:use_htmlunit_snapshot] = true }
opts.on_tail("-h", "--help", "Show this message") { puts opts; exit }
end
parser.parse!
root = Pathname(__FILE__).expand_path.dirname.parent
lib = root + 'lib'
src = root + 'src'
case
when options[:use_htmlunit_snapshot]
require "fileutils"
FileUtils.mkdir_p("vendor/htmlunit")
Dir["vendor/htmlunit/*.jar"].each { |jar| File.unlink(jar) }
Dir.chdir("vendor") do
$stdout.print "Downloading latest snapshot... "
$stdout.flush
%x[curl -O http://build.canoo.com/htmlunit/artifacts/htmlunit-2.8-SNAPSHOT-with-dependencies.zip &> /dev/null]
puts "done"
$stdout.print "Extracting dependencies... "
$stdout.flush
%x[unzip -j -d htmlunit htmlunit-2.8-SNAPSHOT-with-dependencies.zip htmlunit-2.8-SNAPSHOT/lib htmlunit-2.8-SNAPSHOT/lib/* &> /dev/null]
puts "done"
File.unlink "htmlunit-2.8-SNAPSHOT-with-dependencies.zip"
end
$stdout.puts "="*40
$stdout.puts "The latest HtmlUnit snapshot has been extracted to vendor/htmlunit!"
when options[:interactive]
$:.unshift('vendor', lib, src)
require 'rubygems'
require 'akephalos'
require 'akephalos/console'
Akephalos::Console.start
else
- unless socket_file = ARGV[0]
+ unless port = ARGV[0]
puts parser.help
exit
end
if RUBY_PLATFORM == "java"
$:.unshift("vendor", lib, src)
require 'akephalos/server'
- Akephalos::Server.start!(socket_file)
+ Akephalos::Server.start!(port)
else
require 'rubygems'
require 'jruby-jars'
jruby = JRubyJars.core_jar_path
jruby_stdlib = JRubyJars.stdlib_jar_path
java_args = [
"-Xmx128M",
"-cp", [JRubyJars.core_jar_path, JRubyJars.stdlib_jar_path].join(":"),
"org.jruby.Main"
]
ruby_args = [
"-I", "vendor:#{lib}:#{src}",
"-r", "akephalos/server",
- "-e", "Akephalos::Server.start!(#{socket_file.inspect})"
+ "-e", "Akephalos::Server.start!(#{port.inspect})"
]
# Bundler sets ENV["RUBYOPT"] to automatically load bundler/setup.rb, but
# since the akephalos server doesn't have any gem dependencies and is
# always executed with the same context, we clear RUBYOPT before running
# exec.
ENV["RUBYOPT"] = ""
exec("java", *(java_args + ruby_args))
end
end
diff --git a/lib/akephalos/remote_client.rb b/lib/akephalos/remote_client.rb
index a4a0c1d..798805d 100644
--- a/lib/akephalos/remote_client.rb
+++ b/lib/akephalos/remote_client.rb
@@ -1,55 +1,84 @@
+require 'socket'
require 'drb/drb'
# We need to define our own NativeException class for the cases when a native
# exception is raised by the JRuby DRb server.
class NativeException < StandardError; end
module Akephalos
# The +RemoteClient+ class provides an interface to an +Akephalos::Client+
# isntance on a remote DRb server.
#
# == Usage
# client = Akephalos::RemoteClient.new
# client.visit "http://www.oinopa.com"
# client.page.source # => "<!DOCTYPE html PUBLIC..."
class RemoteClient
- @socket_file = "/tmp/akephalos.#{Process.pid}.sock"
-
# Start a remote akephalos server and return the remote Akephalos::Client
# instance.
#
# @return [DRbObject] the remote client instance
def self.new
- start!
+ server_port = start!
+
DRb.start_service
- client = DRbObject.new_with_uri("drbunix://#{@socket_file}")
+ client = DRbObject.new_with_uri("druby://127.0.0.1:#{server_port}")
+
# We want to share our local configuration with the remote server
# process, so we share an undumped version of our configuration. This
# lets us continue to make changes locally and have them reflected in the
# remote process.
client.configuration = Akephalos.configuration.extend(DRbUndumped)
+
client
end
# Start a remote server process and return when it is available for use.
def self.start!
- remote_client = IO.popen("#{Akephalos::BIN_DIR + 'akephalos'} #{@socket_file}")
+ port = find_available_port
+
+ remote_client = IO.popen("#{Akephalos::BIN_DIR + 'akephalos'} #{port}")
# Set up a monitor thread to detect if the forked server exits
# prematurely.
server_monitor = Thread.new { Thread.current[:exited] = Process.wait(remote_client.pid) }
# Wait for the server to be accessible on the socket we specified.
- until File.exists?(@socket_file)
+ until responsive?(port)
exit!(1) if server_monitor[:exited]
sleep 0.5
end
server_monitor.kill
# Ensure that the remote server shuts down gracefully when we are
# finished.
- at_exit { Process.kill(:INT, remote_client.pid); File.unlink(@socket_file) }
+ at_exit { Process.kill(:INT, remote_client.pid) }
+
+ port
+ end
+
+ private
+
+ # @api private
+ # @param [Integer] port the port to check for responsiveness
+ # @return [true, false] whether the port is responsive
+ def self.responsive?(port)
+ socket = TCPSocket.open("127.0.0.1", port)
+ true
+ rescue Errno::ECONNREFUSED
+ false
+ ensure
+ socket.close if socket
+ end
+
+ # @api private
+ # @return [Integer] the next available port
+ def self.find_available_port
+ server = TCPServer.new('127.0.0.1', 0)
+ server.addr[1]
+ ensure
+ server.close if server
end
end
end
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index a28048f..805bafd 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,56 +1,56 @@
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
# @note This method is called by DRb before sending the error to the remote
# connection.
# @return [String] the inner message.
def _dump
to_s
end
end
[
Akephalos::Page,
Akephalos::Node,
Akephalos::Client::Cookies,
Akephalos::Client::Cookies::Cookie
].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
# Akephalos::Server is used by `akephalos --server` to start a DRb server
# serving an instance of Akephalos::Client.
class Server
# Start DRb service for an Akephalos::Client.
#
- # @param [String] socket_file path to socket file to start
- def self.start!(socket_file)
+ # @param [String] port attach server to
+ def self.start!(port)
abort_on_parent_exit!
client = Client.new
- DRb.start_service("drbunix://#{socket_file}", client)
+ DRb.start_service("druby://127.0.0.1:#{port}", client)
DRb.thread.join
end
private
# Exit if STDIN is no longer readable, which corresponds to the process
# which started the server exiting prematurely.
#
# @api private
def self.abort_on_parent_exit!
Thread.new do
begin
STDIN.read
rescue IOError
exit
end
end
end
end
end
|
bernerdschaefer/akephalos
|
2cb9bfa5a0cec2e6ae350bface648875dce11fb6
|
Start server with popen; detect process death
|
diff --git a/lib/akephalos/remote_client.rb b/lib/akephalos/remote_client.rb
index 5dcc223..a4a0c1d 100644
--- a/lib/akephalos/remote_client.rb
+++ b/lib/akephalos/remote_client.rb
@@ -1,57 +1,55 @@
require 'drb/drb'
# We need to define our own NativeException class for the cases when a native
# exception is raised by the JRuby DRb server.
class NativeException < StandardError; end
module Akephalos
# The +RemoteClient+ class provides an interface to an +Akephalos::Client+
# isntance on a remote DRb server.
#
# == Usage
# client = Akephalos::RemoteClient.new
# client.visit "http://www.oinopa.com"
# client.page.source # => "<!DOCTYPE html PUBLIC..."
class RemoteClient
@socket_file = "/tmp/akephalos.#{Process.pid}.sock"
# Start a remote akephalos server and return the remote Akephalos::Client
# instance.
#
# @return [DRbObject] the remote client instance
def self.new
start!
DRb.start_service
client = DRbObject.new_with_uri("drbunix://#{@socket_file}")
# We want to share our local configuration with the remote server
# process, so we share an undumped version of our configuration. This
# lets us continue to make changes locally and have them reflected in the
# remote process.
client.configuration = Akephalos.configuration.extend(DRbUndumped)
client
end
# Start a remote server process and return when it is available for use.
def self.start!
- remote_client = fork do
- exec("#{Akephalos::BIN_DIR + 'akephalos'} #{@socket_file}")
- end
+ remote_client = IO.popen("#{Akephalos::BIN_DIR + 'akephalos'} #{@socket_file}")
# Set up a monitor thread to detect if the forked server exits
# prematurely.
- server_monitor = Thread.new { Thread.current[:exited] = Process.wait }
+ server_monitor = Thread.new { Thread.current[:exited] = Process.wait(remote_client.pid) }
# Wait for the server to be accessible on the socket we specified.
until File.exists?(@socket_file)
exit!(1) if server_monitor[:exited]
- sleep 1
+ sleep 0.5
end
server_monitor.kill
# Ensure that the remote server shuts down gracefully when we are
# finished.
- at_exit { Process.kill(:INT, remote_client); File.unlink(@socket_file) }
+ at_exit { Process.kill(:INT, remote_client.pid); File.unlink(@socket_file) }
end
end
end
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index 5faa695..a28048f 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,39 +1,56 @@
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
# @note This method is called by DRb before sending the error to the remote
# connection.
# @return [String] the inner message.
def _dump
to_s
end
end
[
Akephalos::Page,
Akephalos::Node,
Akephalos::Client::Cookies,
Akephalos::Client::Cookies::Cookie
].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
# Akephalos::Server is used by `akephalos --server` to start a DRb server
# serving an instance of Akephalos::Client.
class Server
# Start DRb service for an Akephalos::Client.
#
# @param [String] socket_file path to socket file to start
def self.start!(socket_file)
+ abort_on_parent_exit!
client = Client.new
DRb.start_service("drbunix://#{socket_file}", client)
DRb.thread.join
end
+
+ private
+
+ # Exit if STDIN is no longer readable, which corresponds to the process
+ # which started the server exiting prematurely.
+ #
+ # @api private
+ def self.abort_on_parent_exit!
+ Thread.new do
+ begin
+ STDIN.read
+ rescue IOError
+ exit
+ end
+ end
+ end
end
end
|
bernerdschaefer/akephalos
|
84ea1f838a069792cf43b4c2b2eebf99c54ffc72
|
Expose API for working with cookies
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 11990ac..8d4642d 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,254 +1,266 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
# Clear all cookie session data.
+ # @deprecated This method is deprecated in Capybara's master branch. Use
+ # {#reset!} instead.
def cleanup!
- browser.clear_cookies
+ reset!
+ end
+
+ # Clear all cookie session data.
+ def reset!
+ cookies.clear
end
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
+ # @return the session cookies
+ def cookies
+ browser.cookies
+ end
+
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index 396e870..9a5b4a1 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,93 +1,94 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
+ require 'akephalos/client/cookies'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
java_import 'com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController'
java_import 'com.gargoylesoftware.htmlunit.SilentCssErrorHandler'
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = WebClient.new
Filter.new(client)
client.setAjaxController(NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(SilentCssErrorHandler.new)
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
- # Clear all cookies for this browser session.
- def clear_cookies
- client.getCookieManager.clearCookies
+ # @return [Cookies] the cookies for this session
+ def cookies
+ @cookies ||= Cookies.new(client.getCookieManager)
end
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/lib/akephalos/client/cookies.rb b/lib/akephalos/client/cookies.rb
new file mode 100644
index 0000000..f0edc65
--- /dev/null
+++ b/lib/akephalos/client/cookies.rb
@@ -0,0 +1,73 @@
+module Akephalos
+ class Client
+ # Interface for working with HtmlUnit's CookieManager, providing a basic
+ # API for manipulating the cookies in a session.
+ class Cookies
+ include Enumerable
+
+ # @param [HtmlUnit::CookieManager] cookie manager
+ def initialize(cookie_manager)
+ @cookie_manager = cookie_manager
+ end
+
+ # @param [name] the cookie name
+ # @return [Cookie] the cookie with the given name
+ # @return [nil] when no cookie is found
+ def [](name)
+ cookie = @cookie_manager.getCookie(name)
+ Cookie.new(cookie) if cookie
+ end
+
+ # Clears all cookies for this session.
+ def clear
+ @cookie_manager.clearCookies
+ end
+
+ # Iterator for all cookies in the current session.
+ def each
+ @cookie_manager.getCookies.each do |cookie|
+ yield Cookie.new(cookie)
+ end
+ end
+
+ # Remove the cookie from the session.
+ #
+ # @param [Cookie] the cookie to remove
+ def delete(cookie)
+ @cookie_manager.removeCookie(cookie.native)
+ end
+
+ # @return [true, false] whether there are any cookies
+ def empty?
+ !any?
+ end
+
+ class Cookie
+
+ attr_reader :domain, :expires, :name, :path, :value
+
+ # @param [HtmlUnit::Cookie] the cookie
+ def initialize(cookie)
+ @_cookie = cookie
+ @domain = cookie.getDomain
+ @expires = cookie.getExpires
+ @name = cookie.getName
+ @path = cookie.getPath
+ @value = cookie.getValue
+ @secure = cookie.isSecure
+ end
+
+ def secure?
+ !!@secure
+ end
+
+ # @return [HtmlUnit::Cookie] the native cookie object
+ # @api private
+ def native
+ @_cookie
+ end
+ end
+
+ end
+ end
+end
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index 61f6529..5faa695 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,34 +1,39 @@
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
# @note This method is called by DRb before sending the error to the remote
# connection.
# @return [String] the inner message.
def _dump
to_s
end
end
-[Akephalos::Page, Akephalos::Node].each { |klass| klass.send(:include, DRbUndumped) }
+[
+ Akephalos::Page,
+ Akephalos::Node,
+ Akephalos::Client::Cookies,
+ Akephalos::Client::Cookies::Cookie
+].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
# Akephalos::Server is used by `akephalos --server` to start a DRb server
# serving an instance of Akephalos::Client.
class Server
# Start DRb service for an Akephalos::Client.
#
# @param [String] socket_file path to socket file to start
def self.start!(socket_file)
client = Client.new
DRb.start_service("drbunix://#{socket_file}", client)
DRb.thread.join
end
end
end
diff --git a/spec/integration/cookies_spec.rb b/spec/integration/cookies_spec.rb
new file mode 100644
index 0000000..311c481
--- /dev/null
+++ b/spec/integration/cookies_spec.rb
@@ -0,0 +1,91 @@
+require 'spec_helper'
+
+describe Capybara::Driver::Akephalos do
+ context 'with akephalos driver' do
+
+ let(:driver) { Capybara::Driver::Akephalos.new(Application) }
+ after { driver.reset! }
+
+ describe "#cookies" do
+ context "when no cookies are set" do
+ it "returns an empty array" do
+ driver.cookies.should be_empty
+ end
+ end
+
+ context "when cookies are set" do
+ before { driver.visit("/set_cookie") }
+
+ it "returns the cookies" do
+ driver.cookies.should_not be_empty
+ end
+
+ describe "#cookies.each" do
+ it "yields cookie objects" do
+ yielded = false
+ driver.cookies.each { yielded = true }
+ yielded.should be_true
+ end
+ end
+
+ describe "#cleanup!" do
+ it "clears the cookies" do
+ driver.cleanup!
+ driver.cookies.should be_empty
+ end
+ end
+
+ describe "#cookies.delete" do
+ it "removes the cookie from the sesison" do
+ driver.cookies.delete(driver.cookies["capybara"])
+ driver.cookies.should be_empty
+ end
+ end
+
+ describe "#cookies[]" do
+ context "when the cookie exists" do
+ it "returns the named cookie" do
+ driver.cookies["capybara"].should_not be_nil
+ end
+
+ context "the cookie" do
+ let(:cookie) { driver.cookies["capybara"] }
+ it "includes the name" do
+ cookie.name.should == "capybara"
+ end
+
+ it "includes the domain" do
+ cookie.domain.should == "localhost"
+ end
+
+ it "includes the path" do
+ cookie.path.should == "/"
+ end
+
+ it "includes the value" do
+ cookie.value.should == "test_cookie"
+ end
+
+ it "includes the expiration" do
+ cookie.expires.should be_nil
+ end
+
+ it "includes security" do
+ cookie.should_not be_secure
+ end
+ end
+
+ end
+ context "when the cookie does not exist" do
+ it "returns nil" do
+ driver.cookies["nonexistant"].should be_nil
+ end
+ end
+ end
+
+ end
+ end
+
+ end
+end
+
|
bernerdschaefer/akephalos
|
397d14338e96efd9d434315f5e2b9ea7dc4083f6
|
Require client before capybara.
|
diff --git a/lib/akephalos.rb b/lib/akephalos.rb
index c8048f3..4f77a8a 100644
--- a/lib/akephalos.rb
+++ b/lib/akephalos.rb
@@ -1,19 +1,19 @@
# **Akephalos** is a cross-platform Ruby interface for *HtmlUnit*, a headless
# browser for the Java platform.
#
# The only requirement is that a Java runtime is available.
#
require 'java' if RUBY_PLATFORM == 'java'
require 'pathname'
-require 'capybara'
module Akephalos
BIN_DIR = Pathname(__FILE__).expand_path.dirname.parent + 'bin'
end
require 'akephalos/client'
+require 'capybara'
require 'akephalos/capybara'
if Object.const_defined? :Cucumber
require 'akephalos/cucumber'
end
|
bernerdschaefer/akephalos
|
229020c3a4e4caa096bbca09c53c7d37a74a0c19
|
Default Capybara's app_host in console
|
diff --git a/lib/akephalos/console.rb b/lib/akephalos/console.rb
index 0e0dcb2..7beb575 100644
--- a/lib/akephalos/console.rb
+++ b/lib/akephalos/console.rb
@@ -1,32 +1,32 @@
# Begin a new Capybara session, by default connecting to localhost on port
# 3000.
def session
- Capybara.app_host = "http://localhost:3000"
+ Capybara.app_host ||= "http://localhost:3000"
@session ||= Capybara::Session.new(:Akephalos)
end
alias page session
module Akephalos
# Simple class for starting an IRB session.
class Console
# Start an IRB session. Tries to load irb/completion, and also loads a
# .irbrc file if it exists.
def self.start
require 'irb'
begin
require 'irb/completion'
rescue Exception
# No readline available, proceed anyway.
end
if ::File.exists? ".irbrc"
ENV['IRBRC'] = ".irbrc"
end
IRB.start
end
end
end
|
bernerdschaefer/akephalos
|
872b08b55168193936b54fb0abf6258f26bf31bb
|
Fix rake release task
|
diff --git a/Rakefile b/Rakefile
index c68a3d4..69ade74 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,41 +1,41 @@
require 'rubygems'
require 'rake'
require 'rake/clean'
JAVA = RUBY_PLATFORM == "java"
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "akephalos/version"
CLEAN.include "*.gem"
task :build do
system "gem build akephalos.gemspec"
end
task "build:java" do
system "export PLATFORM=java && gem build akephalos.gemspec"
end
task "build:all" => ['build', 'build:java']
task :install => (JAVA ? 'build:java' : 'build') do
gemfile = "akephalos-#{Akephalos::VERSION}#{"-java" if JAVA}.gem"
system "gem install #{gemfile}"
end
-task :release => :build_all do
+task :release => 'build:all' do
puts "Tagging #{Akephalos::VERSION}..."
system "git tag -a #{Akephalos::VERSION} -m 'Tagging #{Akephalos::VERSION}'"
puts "Pushing to Github..."
system "git push --tags"
puts "Pushing to Gemcutter..."
["", "-java"].each do |platform|
system "gem push akephalos-#{Akephalos::VERSION}#{platform}.gem"
end
end
load 'tasks/docs.rake'
load 'tasks/spec.rake'
task :default => :spec
|
bernerdschaefer/akephalos
|
852a6c85c2307aa8b0abc36dc63eca021cbc5f7c
|
Bump version to 0.2.4
|
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index 5ad5c2d..01e2e95 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.2.3"
+ VERSION = "0.2.4"
end
|
bernerdschaefer/akephalos
|
73c141054f7b5abd6fc52c4d8a591e81d6a5b232
|
Implement capybara's cleanup! API method
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index c207daa..11990ac 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,249 +1,254 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
# Execute the given block within the context of a specified frame.
#
# @param [String] frame_id the frame's id
# @raise [Capybara::ElementNotFound] if the frame is not found
def within_frame(frame_id, &block)
unless page.within_frame(frame_id, &block)
raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
end
end
+ # Clear all cookie session data.
+ def cleanup!
+ browser.clear_cookies
+ end
+
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index a759321..396e870 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,88 +1,93 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/filter'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
java_import 'com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController'
java_import 'com.gargoylesoftware.htmlunit.SilentCssErrorHandler'
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = WebClient.new
Filter.new(client)
client.setAjaxController(NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(SilentCssErrorHandler.new)
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
+ # Clear all cookies for this browser session.
+ def clear_cookies
+ client.getCookieManager.clearCookies
+ end
+
# @return [Page] the current page
def page
self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
@page
end
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/spec/integration/capybara/driver_spec.rb b/spec/integration/capybara/driver_spec.rb
index be5e8a7..1bc31c5 100644
--- a/spec/integration/capybara/driver_spec.rb
+++ b/spec/integration/capybara/driver_spec.rb
@@ -1,15 +1,16 @@
require 'spec_helper'
describe Capybara::Driver::Akephalos do
before do
@driver = Capybara::Driver::Akephalos.new(TestApp)
end
it_should_behave_like "driver"
it_should_behave_like "driver with javascript support"
it_should_behave_like "driver with header support"
it_should_behave_like "driver with status code support"
it_should_behave_like "driver with frame support"
+ it_should_behave_like "driver with cookies support"
end
|
bernerdschaefer/akephalos
|
a1c5046aabc554b51b044772933369e010c17f08
|
Implement capybara's current_frame API method
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index d87001f..c207daa 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,239 +1,249 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
# @return [Integer] the response's status code
def status_code
page.status_code
end
+ # Execute the given block within the context of a specified frame.
+ #
+ # @param [String] frame_id the frame's id
+ # @raise [Capybara::ElementNotFound] if the frame is not found
+ def within_frame(frame_id, &block)
+ unless page.within_frame(frame_id, &block)
+ raise Capybara::ElementNotFound, "Unable to find frame with id '#{frame_id}'"
+ end
+ end
+
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
diff --git a/lib/akephalos/page.rb b/lib/akephalos/page.rb
index d633d7b..8a762ba 100644
--- a/lib/akephalos/page.rb
+++ b/lib/akephalos/page.rb
@@ -1,80 +1,113 @@
module Akephalos
# Akephalos::Page wraps HtmlUnit's HtmlPage class, exposing an API for
# interacting with a page in the browser.
class Page
# @param [HtmlUnit::HtmlPage] page
def initialize(page)
@nodes = []
@_page = page
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
- nodes = @_page.getByXPath(selector).map { |node| Node.new(node) }
+ nodes = current_frame.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
# Return the page's source, including any JavaScript-triggered DOM changes.
#
# @return [String] the page's modified source
def modified_source
- @_page.asXml
+ current_frame.asXml
end
# Return the page's source as returned by the web server.
#
# @return [String] the page's original source
def source
- @_page.getWebResponse.getContentAsString
+ current_frame.getWebResponse.getContentAsString
end
# @return [Hash{String => String}] the page's response headers
def response_headers
- headers = @_page.getWebResponse.getResponseHeaders.map do |header|
+ headers = current_frame.getWebResponse.getResponseHeaders.map do |header|
[header.getName, header.getValue]
end
Hash[*headers.flatten]
end
# @return [Integer] the response's status code
def status_code
- @_page.getWebResponse.getStatusCode
+ current_frame.getWebResponse.getStatusCode
+ end
+
+ # Execute the given block in the context of the frame specified.
+ #
+ # @param [String] frame_id the frame's id
+ # @return [true] if the frame is found
+ # @return [nil] if the frame is not found
+ def within_frame(frame_id)
+ return unless @current_frame = find_frame(frame_id)
+ yield
+ true
+ ensure
+ @current_frame = nil
end
# @return [String] the current page's URL.
def current_url
- @_page.getWebResponse.getRequestSettings.getUrl.toString
+ current_frame.getWebResponse.getRequestSettings.getUrl.toString
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
- @_page.executeJavaScript(script)
+ current_frame.executeJavaScript(script)
nil
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
- @_page.executeJavaScript(script).getJavaScriptResult
+ current_frame.executeJavaScript(script).getJavaScriptResult
end
# Compare this page with an HtmlUnit page.
#
# @param [HtmlUnit::HtmlPage] other an HtmlUnit page
# @return [true, false]
def ==(other)
@_page == other
end
+
+ private
+
+ # Return the current frame. Usually just @_page, except when inside of the
+ # within_frame block.
+ #
+ # @return [HtmlUnit::HtmlPage] the current frame
+ def current_frame
+ @current_frame || @_page
+ end
+
+ # @param [String] id the frame's id
+ # @return [HtmlUnit::HtmlPage] the specified frame
+ # @return [nil] if no frame is found
+ def find_frame(id)
+ frame = @_page.getFrames.find do |frame|
+ frame.getFrameElement.getAttribute("id") == id
+ end
+ frame.getEnclosedPage if frame
+ end
end
end
diff --git a/spec/integration/capybara/driver_spec.rb b/spec/integration/capybara/driver_spec.rb
index 92ec014..be5e8a7 100644
--- a/spec/integration/capybara/driver_spec.rb
+++ b/spec/integration/capybara/driver_spec.rb
@@ -1,14 +1,15 @@
require 'spec_helper'
describe Capybara::Driver::Akephalos do
before do
@driver = Capybara::Driver::Akephalos.new(TestApp)
end
it_should_behave_like "driver"
it_should_behave_like "driver with javascript support"
it_should_behave_like "driver with header support"
it_should_behave_like "driver with status code support"
+ it_should_behave_like "driver with frame support"
end
|
bernerdschaefer/akephalos
|
f14125d8471a967fe71da3b89bd6e8372b797de3
|
Remove Akephalos::Client::Listener
|
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index 53be002..a759321 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,84 +1,88 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/filter'
- require 'akephalos/client/listener'
module Akephalos
# Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
# point for all interaction with the browser, exposing its current page and
# allowing navigation.
class Client
java_import 'com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController'
java_import 'com.gargoylesoftware.htmlunit.SilentCssErrorHandler'
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = WebClient.new
Filter.new(client)
- client.addWebWindowListener(Listener.new(self))
client.setAjaxController(NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(SilentCssErrorHandler.new)
client
end
Thread.new { @_client.run }
end
# Set the global configuration settings for Akephalos.
#
# @note This is only used when communicating over DRb, since just a
# single client instance is exposed.
# @param [Hash] config the configuration settings
# @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
# Visit the requested URL and return the page.
#
# @param [String] url the URL to load
# @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
+ # @return [Page] the current page
+ def page
+ self.page = client.getCurrentWindow.getTopWindow.getEnclosedPage
+ @page
+ end
+
# Update the current page.
#
# @param [HtmlUnit::HtmlPage] _page the new page
# @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
# Call the future set up in #initialize and return the WebCLient
# instance.
#
# @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
diff --git a/lib/akephalos/client/listener.rb b/lib/akephalos/client/listener.rb
deleted file mode 100644
index 1e8e624..0000000
--- a/lib/akephalos/client/listener.rb
+++ /dev/null
@@ -1,28 +0,0 @@
-module Akephalos
- class Client
- # Listener for events generated by the provided WebClient instance. In
- # particular, we listen for changes to the content of the current window to
- # update the client's current page.
- class Listener
- include com.gargoylesoftware.htmlunit.WebWindowListener
-
- # @param [Akephalos::Client] client instance to update on events
- def initialize(client)
- @client = client
- end
-
- # No-op. Required for API compatibility
- #
- # @api htmlunit
- def webWindowClosed(event)
- end
-
- # Update client with the event's page
- #
- # @api htmlunit
- def webWindowContentChanged(event)
- @client.page = event.getNewPage
- end
- end
- end
-end
|
bernerdschaefer/akephalos
|
632c9efd6e9ff66125046d4b89a3794e5c554cc7
|
Implement capybara's status_code API method
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 66703e2..d87001f 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,234 +1,239 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
# @return [Hash{String => String}] the page's response headers
def response_headers
page.response_headers
end
+ # @return [Integer] the response's status code
+ def status_code
+ page.status_code
+ end
+
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
diff --git a/lib/akephalos/page.rb b/lib/akephalos/page.rb
index 4c8968b..d633d7b 100644
--- a/lib/akephalos/page.rb
+++ b/lib/akephalos/page.rb
@@ -1,75 +1,80 @@
module Akephalos
# Akephalos::Page wraps HtmlUnit's HtmlPage class, exposing an API for
# interacting with a page in the browser.
class Page
# @param [HtmlUnit::HtmlPage] page
def initialize(page)
@nodes = []
@_page = page
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_page.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
# Return the page's source, including any JavaScript-triggered DOM changes.
#
# @return [String] the page's modified source
def modified_source
@_page.asXml
end
# Return the page's source as returned by the web server.
#
# @return [String] the page's original source
def source
@_page.getWebResponse.getContentAsString
end
# @return [Hash{String => String}] the page's response headers
def response_headers
headers = @_page.getWebResponse.getResponseHeaders.map do |header|
[header.getName, header.getValue]
end
Hash[*headers.flatten]
end
+ # @return [Integer] the response's status code
+ def status_code
+ @_page.getWebResponse.getStatusCode
+ end
+
# @return [String] the current page's URL.
def current_url
@_page.getWebResponse.getRequestSettings.getUrl.toString
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
@_page.executeJavaScript(script)
nil
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
@_page.executeJavaScript(script).getJavaScriptResult
end
# Compare this page with an HtmlUnit page.
#
# @param [HtmlUnit::HtmlPage] other an HtmlUnit page
# @return [true, false]
def ==(other)
@_page == other
end
end
end
diff --git a/spec/integration/capybara/driver_spec.rb b/spec/integration/capybara/driver_spec.rb
index 86000ad..92ec014 100644
--- a/spec/integration/capybara/driver_spec.rb
+++ b/spec/integration/capybara/driver_spec.rb
@@ -1,13 +1,14 @@
require 'spec_helper'
describe Capybara::Driver::Akephalos do
before do
@driver = Capybara::Driver::Akephalos.new(TestApp)
end
it_should_behave_like "driver"
it_should_behave_like "driver with javascript support"
it_should_behave_like "driver with header support"
+ it_should_behave_like "driver with status code support"
end
|
bernerdschaefer/akephalos
|
b312e9197ab92c61ae40cfbbb4cd40d413ab11ea
|
Implement capybara's response_headers API method
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index 3bc2d90..66703e2 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,229 +1,234 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
# @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
# Visit the given path in the browser.
#
# @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
# @return [String] the page's original source
def source
page.source
end
# @return [String] the page's modified source
def body
page.modified_source
end
+ # @return [Hash{String => String}] the page's response headers
+ def response_headers
+ page.response_headers
+ end
+
# @return [String] the page's current URL
def current_url
page.current_url
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector XPath query
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
page.execute_script script
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
# @return the current page
def page
browser.page
end
# @return the browser
def browser
self.class.driver
end
# Disable waiting in Capybara, since waiting is handled directly by
# Akephalos.
#
# @return [false]
def wait
false
end
private
# @param [String] path
# @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
diff --git a/lib/akephalos/page.rb b/lib/akephalos/page.rb
index 54354db..4c8968b 100644
--- a/lib/akephalos/page.rb
+++ b/lib/akephalos/page.rb
@@ -1,67 +1,75 @@
module Akephalos
# Akephalos::Page wraps HtmlUnit's HtmlPage class, exposing an API for
# interacting with a page in the browser.
class Page
# @param [HtmlUnit::HtmlPage] page
def initialize(page)
@nodes = []
@_page = page
end
# Search for nodes which match the given XPath selector.
#
# @param [String] selector an XPath selector
# @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_page.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
# Return the page's source, including any JavaScript-triggered DOM changes.
#
# @return [String] the page's modified source
def modified_source
@_page.asXml
end
# Return the page's source as returned by the web server.
#
# @return [String] the page's original source
def source
@_page.getWebResponse.getContentAsString
end
+ # @return [Hash{String => String}] the page's response headers
+ def response_headers
+ headers = @_page.getWebResponse.getResponseHeaders.map do |header|
+ [header.getName, header.getValue]
+ end
+ Hash[*headers.flatten]
+ end
+
# @return [String] the current page's URL.
def current_url
@_page.getWebResponse.getRequestSettings.getUrl.toString
end
# Execute JavaScript against the current page, discarding any return value.
#
# @param [String] script the JavaScript to be executed
# @return [nil]
def execute_script(script)
@_page.executeJavaScript(script)
nil
end
# Execute JavaScript against the current page and return the results.
#
# @param [String] script the JavaScript to be executed
# @return the result of the JavaScript
def evaluate_script(script)
@_page.executeJavaScript(script).getJavaScriptResult
end
# Compare this page with an HtmlUnit page.
#
# @param [HtmlUnit::HtmlPage] other an HtmlUnit page
# @return [true, false]
def ==(other)
@_page == other
end
end
end
diff --git a/spec/integration/capybara/driver_spec.rb b/spec/integration/capybara/driver_spec.rb
index d9dd670..86000ad 100644
--- a/spec/integration/capybara/driver_spec.rb
+++ b/spec/integration/capybara/driver_spec.rb
@@ -1,12 +1,13 @@
require 'spec_helper'
describe Capybara::Driver::Akephalos do
before do
@driver = Capybara::Driver::Akephalos.new(TestApp)
end
it_should_behave_like "driver"
it_should_behave_like "driver with javascript support"
+ it_should_behave_like "driver with header support"
end
|
bernerdschaefer/akephalos
|
5cc52adcbe7754c7193559ea2637a4ba4b8f95fd
|
Fix link to API docs in readme
|
diff --git a/README.md b/README.md
index 871a678..25aa6d7 100644
--- a/README.md
+++ b/README.md
@@ -1,56 +1,56 @@
# Akephalos
Akephalos is a full-stack headless browser for integration testing with
Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
## Installation
gem install akephalos
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
require 'akephalos'
Capybara.javascript_driver = :akephalos
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
## More
* [bin/akephalos](http://bernerdschaefer.github.com/akephalos/akephalos-bin.html)
allows you to start an interactive shell or DRb server, as well as perform
other maintenance features.
* [Filters](http://bernerdschaefer.github.com/akephalos/filters.html) allows
you to declare mock responses for external resources and services requested
by the browser.
## Resources
-* [API Documentation](http://github.com/bernerdschaefer/akephalos/api)
+* [API Documentation](http://bernerdschaefer.github.com/akephalos/api)
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
|
bernerdschaefer/akephalos
|
f9990078efc49ab3f752b52b0ee110b271caa592
|
Add sample application to spec/support
|
diff --git a/spec/integration/slow_page_loads_spec.rb b/spec/integration/slow_page_loads_spec.rb
index 6ebe2f7..5ddea14 100644
--- a/spec/integration/slow_page_loads_spec.rb
+++ b/spec/integration/slow_page_loads_spec.rb
@@ -1,61 +1,27 @@
require 'spec_helper'
-class SlowApp < TestApp
- get '/slow_page' do
- sleep 1
- "<p>Loaded!</p>"
- end
-
- get '/slow_ajax_load' do
- <<-HTML
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
- <title>with_js</title>
- <script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
- <script type="text/javascript">
- $(function() {
- $('#ajax_load').click(function() {
- $('body').load('/slow_page');
- return false;
- });
- });
- </script>
- </head>
- <body>
- <a href="#" id="ajax_load">Click me</a>
- </body>
- HTML
- end
-end
-
-if $0 == __FILE__
- if __FILE__ == $0
- Rack::Handler::Mongrel.run SlowApp, :Port => 8070
- end
-end
-
describe Capybara::Session do
context 'with akephalos driver' do
before do
- @session = Capybara::Session.new(:akephalos, SlowApp)
+ @session = Capybara::Session.new(:akephalos, Application)
end
context "slow page load" do
it "should wait for the page to finish loading" do
@session.visit('/slow_page')
@session.current_url.should include('/slow_page')
end
end
context "slow ajax load" do
it "should wait for ajax to load" do
@session.visit('/slow_ajax_load')
@session.click_link('Click me')
@session.should have_xpath("//p[contains(.,'Loaded!')]")
end
end
end
end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 9b9d53f..028bd00 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,19 +1,20 @@
require 'rubygems'
root = File.expand_path('../../', __FILE__)
%w(vendor lib src).each do |dir|
dir = File.join(root, dir)
$:.unshift dir unless $:.include?(dir)
end
require 'akephalos'
spec_dir = nil
$:.detect do |dir|
if File.exists? File.join(dir, "capybara.rb")
spec_dir = File.expand_path(File.join(dir,"..","spec"))
$:.unshift( spec_dir )
end
end
require File.join(spec_dir,"spec_helper")
+require "spec/support/application"
diff --git a/spec/support/application.rb b/spec/support/application.rb
new file mode 100644
index 0000000..ec285b9
--- /dev/null
+++ b/spec/support/application.rb
@@ -0,0 +1,32 @@
+class Application < TestApp
+ get '/slow_page' do
+ sleep 1
+ "<p>Loaded!</p>"
+ end
+
+ get '/slow_ajax_load' do
+ <<-HTML
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
+ <title>with_js</title>
+ <script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
+ <script type="text/javascript">
+ $(function() {
+ $('#ajax_load').click(function() {
+ $('body').load('/slow_page');
+ return false;
+ });
+ });
+ </script>
+ </head>
+ <body>
+ <a href="#" id="ajax_load">Click me</a>
+ </body>
+ HTML
+ end
+end
+
+if $0 == __FILE__
+ Rack::Handler::Mongrel.run Application, :Port => 8070
+end
+
|
bernerdschaefer/akephalos
|
6b229e25010006e8273921312838be4150e030d2
|
Cleanup unused parts of slow_page_loads_spec
|
diff --git a/spec/integration/slow_page_loads_spec.rb b/spec/integration/slow_page_loads_spec.rb
index 047f67c..6ebe2f7 100644
--- a/spec/integration/slow_page_loads_spec.rb
+++ b/spec/integration/slow_page_loads_spec.rb
@@ -1,66 +1,61 @@
require 'spec_helper'
class SlowApp < TestApp
get '/slow_page' do
sleep 1
"<p>Loaded!</p>"
end
- get '/really_slow_page' do
- sleep 5
- end
-
get '/slow_ajax_load' do
<<-HTML
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>with_js</title>
<script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$('#ajax_load').click(function() {
- // $('body').html("<p>Loaded!</p>");
$('body').load('/slow_page');
return false;
});
});
</script>
</head>
<body>
<a href="#" id="ajax_load">Click me</a>
</body>
HTML
end
end
if $0 == __FILE__
if __FILE__ == $0
Rack::Handler::Mongrel.run SlowApp, :Port => 8070
end
end
describe Capybara::Session do
context 'with akephalos driver' do
before do
@session = Capybara::Session.new(:akephalos, SlowApp)
end
context "slow page load" do
it "should wait for the page to finish loading" do
@session.visit('/slow_page')
@session.current_url.should include('/slow_page')
end
end
context "slow ajax load" do
it "should wait for ajax to load" do
@session.visit('/slow_ajax_load')
@session.click_link('Click me')
@session.should have_xpath("//p[contains(.,'Loaded!')]")
end
end
end
end
|
bernerdschaefer/akephalos
|
88623732c1702e610300db551ae72c1024ef469a
|
Add link to API documentation
|
diff --git a/README.md b/README.md
index d0c9b54..871a678 100644
--- a/README.md
+++ b/README.md
@@ -1,55 +1,56 @@
# Akephalos
Akephalos is a full-stack headless browser for integration testing with
Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
## Installation
gem install akephalos
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
require 'akephalos'
Capybara.javascript_driver = :akephalos
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
## More
* [bin/akephalos](http://bernerdschaefer.github.com/akephalos/akephalos-bin.html)
allows you to start an interactive shell or DRb server, as well as perform
other maintenance features.
* [Filters](http://bernerdschaefer.github.com/akephalos/filters.html) allows
you to declare mock responses for external resources and services requested
by the browser.
## Resources
+* [API Documentation](http://github.com/bernerdschaefer/akephalos/api)
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
diff --git a/docs/index.html.haml b/docs/index.html.haml
index 952c576..7cdcff6 100644
--- a/docs/index.html.haml
+++ b/docs/index.html.haml
@@ -1,67 +1,68 @@
%section
:markdown
Akephalos is a full-stack headless browser for integration testing with
Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
%section
:markdown
## Installation
%aside
:bash
gem install akephalos
%section
:markdown
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
%aside
:code
require 'akephalos'
Capybara.javascript_driver = :akephalos
%section
:markdown
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
%aside
:code
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
%section
:markdown
## More
* [bin/akephalos](akephalos-bin.html) allows you to start an interactive
shell or DRb server, as well as perform other maintenance features.
* [Filters](filters.html) allows you to declare mock responses for
external resources and services requested by the browser.
## Resources
+ * [API Documentation](http://bernerdschaefer.github.com/akephalos/api)
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
|
bernerdschaefer/akephalos
|
0440a875c7144f283a8b9a6cff7b621e1c2f5453
|
Document NameError::Message#_dump
|
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index 4a963dc..61f6529 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,31 +1,34 @@
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
+ # @note This method is called by DRb before sending the error to the remote
+ # connection.
+ # @return [String] the inner message.
def _dump
to_s
end
end
[Akephalos::Page, Akephalos::Node].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
# Akephalos::Server is used by `akephalos --server` to start a DRb server
# serving an instance of Akephalos::Client.
class Server
# Start DRb service for an Akephalos::Client.
#
# @param [String] socket_file path to socket file to start
def self.start!(socket_file)
client = Client.new
DRb.start_service("drbunix://#{socket_file}", client)
DRb.thread.join
end
end
end
|
bernerdschaefer/akephalos
|
177e18d472a2d21c9a106c5f1af78c6b70cbf230
|
Document Capybara::Driver::Akephalos
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index b99830c..3bc2d90 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,202 +1,229 @@
# Driver class exposed to Capybara. It implements Capybara's full driver API,
# and is the entry point for interaction between the test suites and HtmlUnit.
#
# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
# Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
# @api capybara
# @param [String] name attribute name
# @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
# @api capybara
# @return [String] the inner text of the node
def text
node.text
end
# @api capybara
# @return [String] the form element's value
def value
node.value
end
# Set the form element's value.
#
# @api capybara
# @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
# Select an option from a select box.
#
# @api capybara
# @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Unselect an option from a select box.
#
# @api capybara
# @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
# Trigger an event on the element.
#
# @api capybara
# @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
# @api capybara
# @return [String] the element's tag name
def tag_name
node.tag_name
end
# @api capybara
# @return [true, false] the element's visiblity
def visible?
node.visible?
end
# Drag the element on top of the target element.
#
# @api capybara
# @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
# Click the element.
def click
node.click
end
private
# Return all child nodes which match the selector criteria.
#
# @api capybara
# @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
# @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
+ # @return [Client] an instance of Akephalos::Client
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
+ # Visit the given path in the browser.
+ #
+ # @param [String] path relative path to visit
def visit(path)
browser.visit(url(path))
end
+ # @return [String] the page's original source
def source
page.source
end
+ # @return [String] the page's modified source
def body
page.modified_source
end
+ # @return [String] the page's current URL
def current_url
page.current_url
end
+ # Search for nodes which match the given XPath selector.
+ #
+ # @param [String] selector XPath query
+ # @return [Array<Node>] the matched nodes
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
+ # Execute JavaScript against the current page, discarding any return value.
+ #
+ # @param [String] script the JavaScript to be executed
+ # @return [nil]
def execute_script(script)
page.execute_script script
end
+ # Execute JavaScript against the current page and return the results.
+ #
+ # @param [String] script the JavaScript to be executed
+ # @return the result of the JavaScript
def evaluate_script(script)
page.evaluate_script script
end
+ # @return the current page
def page
browser.page
end
+ # @return the browser
def browser
self.class.driver
end
+ # Disable waiting in Capybara, since waiting is handled directly by
+ # Akephalos.
+ #
+ # @return [false]
def wait
false
end
-private
+ private
+ # @param [String] path
+ # @return [String] the absolute URL for the given path
def url(path)
rack_server.url(path)
end
end
|
bernerdschaefer/akephalos
|
098fc3fec80086f67a393963cb5455faf2524b0a
|
Document Capybara::Driver::Akephalos::Node
|
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
index a56a259..b99830c 100644
--- a/lib/akephalos/capybara.rb
+++ b/lib/akephalos/capybara.rb
@@ -1,158 +1,202 @@
+# Driver class exposed to Capybara. It implements Capybara's full driver API,
+# and is the entry point for interaction between the test suites and HtmlUnit.
+#
+# This class and +Capybara::Driver::Akephalos::Node+ are written to run on both
+# MRI and JRuby, and is agnostic whether the Akephalos::Client instance is used
+# directly or over DRb.
class Capybara::Driver::Akephalos < Capybara::Driver::Base
+ # Akephalos-specific implementation for Capybara's Node class.
class Node < Capybara::Node
+ # @api capybara
+ # @param [String] name attribute name
+ # @return [String] the attribute value
def [](name)
name = name.to_s
case name
when 'checked'
node.checked?
else
node[name.to_s]
end
end
+ # @api capybara
+ # @return [String] the inner text of the node
def text
node.text
end
+ # @api capybara
+ # @return [String] the form element's value
def value
node.value
end
+ # Set the form element's value.
+ #
+ # @api capybara
+ # @param [String] value the form element's new value
def set(value)
if tag_name == 'textarea'
node.value = value.to_s
elsif tag_name == 'input' and type == 'radio'
click
elsif tag_name == 'input' and type == 'checkbox'
if value != self['checked']
click
end
elsif tag_name == 'input'
node.value = value.to_s
end
end
+ # Select an option from a select box.
+ #
+ # @api capybara
+ # @param [String] option the option to select
def select(option)
result = node.select_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
+ # Unselect an option from a select box.
+ #
+ # @api capybara
+ # @param [String] option the option to unselect
def unselect(option)
unless self[:multiple]
raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
end
result = node.unselect_option(option)
if result == nil
options = node.options.map(&:text).join(", ")
raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
else
result
end
end
+ # Trigger an event on the element.
+ #
+ # @api capybara
+ # @param [String] event the event to trigger
def trigger(event)
node.fire_event(event.to_s)
end
+ # @api capybara
+ # @return [String] the element's tag name
def tag_name
node.tag_name
end
+ # @api capybara
+ # @return [true, false] the element's visiblity
def visible?
node.visible?
end
+ # Drag the element on top of the target element.
+ #
+ # @api capybara
+ # @param [Node] element the target element
def drag_to(element)
trigger('mousedown')
element.trigger('mousemove')
element.trigger('mouseup')
end
+ # Click the element.
def click
node.click
end
private
+ # Return all child nodes which match the selector criteria.
+ #
+ # @api capybara
+ # @return [Array<Node>] the matched nodes
def all_unfiltered(selector)
nodes = []
node.find(selector).each { |node| nodes << Node.new(driver, node) }
nodes
end
+ # @return [String] the node's type attribute
def type
node[:type]
end
end
attr_reader :app, :rack_server
def self.driver
@driver ||= Akephalos::Client.new
end
def initialize(app)
@app = app
@rack_server = Capybara::Server.new(@app)
@rack_server.boot if Capybara.run_server
end
def visit(path)
browser.visit(url(path))
end
def source
page.source
end
def body
page.modified_source
end
def current_url
page.current_url
end
def find(selector)
nodes = []
page.find(selector).each { |node| nodes << Node.new(self, node) }
nodes
end
def execute_script(script)
page.execute_script script
end
def evaluate_script(script)
page.evaluate_script script
end
def page
browser.page
end
def browser
self.class.driver
end
def wait
false
end
private
def url(path)
rack_server.url(path)
end
end
|
bernerdschaefer/akephalos
|
3027c42ef16f9d1d882f9c8323feb572680fd044
|
Document Akephalos::Console
|
diff --git a/lib/akephalos/console.rb b/lib/akephalos/console.rb
index b33c7e0..0e0dcb2 100644
--- a/lib/akephalos/console.rb
+++ b/lib/akephalos/console.rb
@@ -1,27 +1,32 @@
+# Begin a new Capybara session, by default connecting to localhost on port
+# 3000.
def session
Capybara.app_host = "http://localhost:3000"
@session ||= Capybara::Session.new(:Akephalos)
end
alias page session
module Akephalos
+ # Simple class for starting an IRB session.
class Console
+ # Start an IRB session. Tries to load irb/completion, and also loads a
+ # .irbrc file if it exists.
def self.start
require 'irb'
begin
require 'irb/completion'
rescue Exception
# No readline available, proceed anyway.
end
if ::File.exists? ".irbrc"
ENV['IRBRC'] = ".irbrc"
end
IRB.start
end
end
end
|
bernerdschaefer/akephalos
|
4c67a9a4844a965ab5c011cdc121e59ba48f0aa0
|
Document Akephalos::Server
|
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index ee4131c..4a963dc 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,25 +1,31 @@
-# This file runs a JRuby DRb server, and is run by `akephalos --server`.
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
def _dump
to_s
end
end
[Akephalos::Page, Akephalos::Node].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
+
+ # Akephalos::Server is used by `akephalos --server` to start a DRb server
+ # serving an instance of Akephalos::Client.
class Server
+ # Start DRb service for an Akephalos::Client.
+ #
+ # @param [String] socket_file path to socket file to start
def self.start!(socket_file)
client = Client.new
DRb.start_service("drbunix://#{socket_file}", client)
DRb.thread.join
end
end
+
end
|
bernerdschaefer/akephalos
|
ad72eb92f05d164266b02e8d4e2285825200ef87
|
Document Akephalos::Client
|
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
index a8d3116..53be002 100644
--- a/lib/akephalos/client.rb
+++ b/lib/akephalos/client.rb
@@ -1,61 +1,84 @@
require 'akephalos/configuration'
if RUBY_PLATFORM != "java"
require 'akephalos/remote_client'
Akephalos::Client = Akephalos::RemoteClient
else
require 'akephalos/htmlunit'
require 'akephalos/htmlunit/ext/http_method'
require 'akephalos/page'
require 'akephalos/node'
require 'akephalos/client/filter'
require 'akephalos/client/listener'
module Akephalos
+
+ # Akephalos::Client wraps HtmlUnit's WebClient class. It is the main entry
+ # point for all interaction with the browser, exposing its current page and
+ # allowing navigation.
class Client
java_import 'com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController'
java_import 'com.gargoylesoftware.htmlunit.SilentCssErrorHandler'
attr_reader :page
def initialize
@_client = java.util.concurrent.FutureTask.new do
client = WebClient.new
Filter.new(client)
client.addWebWindowListener(Listener.new(self))
client.setAjaxController(NicelyResynchronizingAjaxController.new)
client.setCssErrorHandler(SilentCssErrorHandler.new)
client
end
Thread.new { @_client.run }
end
+ # Set the global configuration settings for Akephalos.
+ #
+ # @note This is only used when communicating over DRb, since just a
+ # single client instance is exposed.
+ # @param [Hash] config the configuration settings
+ # @return [Hash] the configuration
def configuration=(config)
Akephalos.configuration = config
end
+ # Visit the requested URL and return the page.
+ #
+ # @param [String] url the URL to load
+ # @return [Page] the loaded page
def visit(url)
client.getPage(url)
page
end
+ # Update the current page.
+ #
+ # @param [HtmlUnit::HtmlPage] _page the new page
+ # @return [Page] the new page
def page=(_page)
if @page != _page
@page = Page.new(_page)
end
@page
end
private
+
+ # Call the future set up in #initialize and return the WebCLient
+ # instance.
+ #
+ # @return [HtmlUnit::WebClient] the WebClient instance
def client
@client ||= @_client.get.tap do |client|
client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
end
end
end
end
end
|
bernerdschaefer/akephalos
|
cb70eeefc5926a17ca9204f48c3be13fb85498b5
|
Document Akephalos::Page
|
diff --git a/lib/akephalos/page.rb b/lib/akephalos/page.rb
index 359bcd9..54354db 100644
--- a/lib/akephalos/page.rb
+++ b/lib/akephalos/page.rb
@@ -1,39 +1,67 @@
module Akephalos
+
+ # Akephalos::Page wraps HtmlUnit's HtmlPage class, exposing an API for
+ # interacting with a page in the browser.
class Page
+ # @param [HtmlUnit::HtmlPage] page
def initialize(page)
@nodes = []
@_page = page
end
+ # Search for nodes which match the given XPath selector.
+ #
+ # @param [String] selector an XPath selector
+ # @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_page.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
+ # Return the page's source, including any JavaScript-triggered DOM changes.
+ #
+ # @return [String] the page's modified source
def modified_source
@_page.asXml
end
+ # Return the page's source as returned by the web server.
+ #
+ # @return [String] the page's original source
def source
@_page.getWebResponse.getContentAsString
end
+ # @return [String] the current page's URL.
def current_url
@_page.getWebResponse.getRequestSettings.getUrl.toString
end
+ # Execute JavaScript against the current page, discarding any return value.
+ #
+ # @param [String] script the JavaScript to be executed
+ # @return [nil]
def execute_script(script)
@_page.executeJavaScript(script)
nil
end
+ # Execute JavaScript against the current page and return the results.
+ #
+ # @param [String] script the JavaScript to be executed
+ # @return the result of the JavaScript
def evaluate_script(script)
@_page.executeJavaScript(script).getJavaScriptResult
end
+ # Compare this page with an HtmlUnit page.
+ #
+ # @param [HtmlUnit::HtmlPage] other an HtmlUnit page
+ # @return [true, false]
def ==(other)
@_page == other
end
end
+
end
|
bernerdschaefer/akephalos
|
e6693efc857a353a302c7675c9b092d522f1be98
|
Document Akephalos::Node
|
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
index 5c99a4a..fb2a413 100644
--- a/lib/akephalos/node.rb
+++ b/lib/akephalos/node.rb
@@ -1,89 +1,136 @@
module Akephalos
+
+ # Akephalos::Node wraps HtmlUnit's DOMNode class, providing a simple API for
+ # interacting with an element on the page.
class Node
+ # @param [HtmlUnit::DOMNode] node
def initialize(node)
@nodes = []
@_node = node
end
+ # @return [true, false] whether the element is checked
def checked?
@_node.isChecked
end
+ # @return [String] inner text of the node
def text
@_node.asText
end
+ # Return the value of the node's attribute.
+ #
+ # @param [String] name attribute on node
+ # @return [String] the value of the named attribute
+ # @return [nil] when the node does not have the named attribute
def [](name)
@_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
end
+ # Return the value of a form element. If the element is a select box and
+ # has "multiple" declared as an attribute, then all selected options will
+ # be returned as an array.
+ #
+ # @return [String, Array<String>] the node's value
def value
case tag_name
when "select"
if self[:multiple]
@_node.selected_options.map { |option| option.text }
else
selected_option = @_node.selected_options.first
selected_option ? selected_option.text : nil
end
when "textarea"
@_node.getText
else
self[:value]
end
end
+ # Set the value of the form input.
+ #
+ # @param [String] value
def value=(value)
case tag_name
when "textarea"
@_node.setText(value)
when "input"
@_node.setValueAttribute(value)
end
end
+ # Select an option from a select box by its value.
+ #
+ # @return [true, false] whether the selection was successful
def select_option(option)
opt = @_node.getOptions.detect { |o| o.asText == option }
opt && opt.setSelected(true)
end
+ # Unselect an option from a select box by its value.
+ #
+ # @return [true, false] whether the unselection was successful
def unselect_option(option)
opt = @_node.getOptions.detect { |o| o.asText == option }
opt && opt.setSelected(false)
end
+ # Return the option elements for a select box.
+ #
+ # @return [Array<Node>] the options
def options
@_node.getOptions.map { |node| Node.new(node) }
end
+ # Return the selected option elements for a select box.
+ #
+ # @return [Array<Node>] the selected options
def selected_options
@_node.getSelectedOptions.map { |node| Node.new(node) }
end
+ # Fire a JavaScript event on the current node. Note that you should not
+ # prefix event names with "on", so:
+ #
+ # link.fire_event('mousedown')
+ #
+ # @param [String] JavaScript event name
def fire_event(name)
@_node.fireEvent(name)
end
+ # @return [String] the node's tag name
def tag_name
@_node.getNodeName
end
+ # @return [true, false] whether the node is visible to the user accounting
+ # for CSS.
def visible?
@_node.isDisplayed
end
+ # Click the node and then wait for any triggered JavaScript callbacks to
+ # fire.
def click
@_node.click
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
@_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
end
+ # Search for child nodes which match the given XPath selector.
+ #
+ # @param [String] selector an XPath selector
+ # @return [Array<Node>] the matched nodes
def find(selector)
nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
@nodes << nodes
nodes
end
end
+
end
|
bernerdschaefer/akephalos
|
bb967df7253ed43bce0f54d852d4a789b22992ba
|
Document akephalos/configuration
|
diff --git a/lib/akephalos/configuration.rb b/lib/akephalos/configuration.rb
index 3527f58..8ad090f 100644
--- a/lib/akephalos/configuration.rb
+++ b/lib/akephalos/configuration.rb
@@ -1,21 +1,49 @@
module Akephalos
@configuration = {}
class << self
+ # @return [Hash] the configuration
attr_accessor :configuration
end
module Filters
+ # @return [Array] all defined filters
def filters
configuration[:filters] ||= []
end
+ # Defines a new filter to be tested by Akephalos::Filter when executing
+ # page requests. An HTTP method and a regex or string to match against the
+ # URL are required for defining a filter.
+ #
+ # You can additionally pass the following options to define how the
+ # filtered request should respond:
+ #
+ # :status (defaults to 200)
+ # :body (defaults to "")
+ # :headers (defaults to {})
+ #
+ # If we define a filter with no additional options, then, we will get an
+ # empty HTML response:
+ #
+ # Akephalos.filter :post, "http://example.com"
+ # Akephalos.filter :any, %r{http://.*\.com}
+ #
+ # If you instead, say, wanted to simulate a failure in an external system,
+ # you could do this:
+ #
+ # Akephalos.filter :post, "http://example.com",
+ # :status => 500, :body => "Something went wrong"
+ #
+ # @param [Symbol] method the HTTP method to match
+ # @param [RegExp, String] regex URL matcher
+ # @param [Hash] options response values
def filter(method, regex, options = {})
regex = Regexp.new(Regexp.escape(regex)) if regex.is_a?(String)
filters << {:method => method, :filter => regex, :status => 200, :body => "", :headers => {}}.merge!(options)
end
end
extend Filters
end
|
bernerdschaefer/akephalos
|
ef03930660b0a8b2142d6052e3d1538edb5a3b47
|
Refactor configuration getter and setter
|
diff --git a/lib/akephalos/configuration.rb b/lib/akephalos/configuration.rb
index b600c0d..3527f58 100644
--- a/lib/akephalos/configuration.rb
+++ b/lib/akephalos/configuration.rb
@@ -1,22 +1,21 @@
module Akephalos
- def self.configuration
- @configuration ||= {}
- end
- def self.configuration=(config)
- @configuration = config
+ @configuration = {}
+
+ class << self
+ attr_accessor :configuration
end
module Filters
def filters
configuration[:filters] ||= []
end
def filter(method, regex, options = {})
regex = Regexp.new(Regexp.escape(regex)) if regex.is_a?(String)
filters << {:method => method, :filter => regex, :status => 200, :body => "", :headers => {}}.merge!(options)
end
end
extend Filters
end
|
bernerdschaefer/akephalos
|
8a6e3a315db12813163892b342d7f938ae14c912
|
Document HttpMethod extension
|
diff --git a/lib/akephalos/htmlunit/ext/http_method.rb b/lib/akephalos/htmlunit/ext/http_method.rb
index ed2d7cb..610ef42 100644
--- a/lib/akephalos/htmlunit/ext/http_method.rb
+++ b/lib/akephalos/htmlunit/ext/http_method.rb
@@ -1,18 +1,28 @@
+# Reopen com.gargoylesoftware.htmlunit.HttpMethod to add convenience methods.
class HttpMethod
+
+ # Loosely compare HttpMethod with another object, accepting either an
+ # HttpMethod instance or a symbol describing the method. Note that :any is a
+ # special symbol which will always return true.
+ #
+ # @param [HttpMethod] other an HtmlUnit HttpMethod object
+ # @param [Symbol] other a symbolized representation of an http method
+ # @return [true/false]
def ===(other)
case other
when HttpMethod
super
when :any
true
when :get
self == self.class::GET
when :post
self == self.class::POST
when :put
self == self.class::PUT
when :delete
self == self.class::DELETE
end
end
+
end
|
bernerdschaefer/akephalos
|
16c8e1aeaffbd18e83972f33843f1f52f2575484
|
Document Akephalos::Client::Listener
|
diff --git a/lib/akephalos/client/listener.rb b/lib/akephalos/client/listener.rb
index b2fbdcc..1e8e624 100644
--- a/lib/akephalos/client/listener.rb
+++ b/lib/akephalos/client/listener.rb
@@ -1,18 +1,28 @@
module Akephalos
class Client
+ # Listener for events generated by the provided WebClient instance. In
+ # particular, we listen for changes to the content of the current window to
+ # update the client's current page.
class Listener
include com.gargoylesoftware.htmlunit.WebWindowListener
+ # @param [Akephalos::Client] client instance to update on events
def initialize(client)
@client = client
end
+ # No-op. Required for API compatibility
+ #
+ # @api htmlunit
def webWindowClosed(event)
end
+ # Update client with the event's page
+ #
+ # @api htmlunit
def webWindowContentChanged(event)
@client.page = event.getNewPage
end
end
end
end
|
bernerdschaefer/akephalos
|
ce24a5b5d7190b12252c3d04c26cde1ca48fb988
|
Document Akepahlos::Client::Filter
|
diff --git a/lib/akephalos/client/filter.rb b/lib/akephalos/client/filter.rb
index 3cc1cb7..0c86fc9 100644
--- a/lib/akephalos/client/filter.rb
+++ b/lib/akephalos/client/filter.rb
@@ -1,82 +1,122 @@
module Akephalos
class Client
+
+ # Akephalos::Client::Filter extends HtmlUnit's WebConnectionWrapper to
+ # enable filtering outgoing requests generated interally by HtmlUnit.
+ #
+ # When a request comes through, it will be tested against the filters
+ # defined in Akephalos.filters and return a mock response if a match is
+ # found. If no filters are defined, or no filters match the request, then
+ # the response will bubble up to HtmlUnit for the normal request/response
+ # cycle.
class Filter < WebConnectionWrapper
java_import 'com.gargoylesoftware.htmlunit.util.NameValuePair'
java_import 'com.gargoylesoftware.htmlunit.WebResponseData'
java_import 'com.gargoylesoftware.htmlunit.WebResponseImpl'
+ # Filters an outgoing request, and if a match is found, returns the mock
+ # response.
+ #
+ # @param [WebRequest] request the pending HTTP request
+ # @return [WebResponseImpl] when the request matches a defined filter
+ # @return [nil] when no filters match the request
def filter(request)
- if filter = Akephalos.filters.find { |filter| request.http_method === filter[:method] && request.url.to_s =~ filter[:filter] }
+ if filter = find_filter(request)
start_time = Time.now
headers = filter[:headers].map { |name, value| NameValuePair.new(name.to_s, value.to_s) }
- response = WebResponseData.new(filter[:body].to_s.to_java_bytes, filter[:status], HTTP_STATUS_CODES.fetch(filter[:status], "Unknown"), headers)
+ response = WebResponseData.new(
+ filter[:body].to_s.to_java_bytes,
+ filter[:status],
+ HTTP_STATUS_CODES.fetch(filter[:status], "Unknown"),
+ headers
+ )
WebResponseImpl.new(response, request, Time.now - start_time)
end
end
+ # Searches for a filter which matches the request's HTTP method and url.
+ #
+ # @param [WebRequest] request the pending HTTP request
+ # @return [Hash] when a filter matches the request
+ # @return [nil] when no filters match the request
+ def find_filter(request)
+ Akephalos.filters.find do |filter|
+ request.http_method === filter[:method] && request.url.to_s =~ filter[:filter]
+ end
+ end
+
+ # This method is called by WebClient when a page is requested, and will
+ # return a mock response if the request matches a defined filter or else
+ # return the actual response.
+ #
+ # @api htmlunit
+ # @param [WebRequest] request the pending HTTP request
+ # @return [WebResponseImpl]
def getResponse(request)
filter(request) || super
end
+ # Map of status codes to their English descriptions.
HTTP_STATUS_CODES = {
100 => "Continue",
101 => "Switching Protocols",
102 => "Processing",
200 => "OK",
201 => "Created",
202 => "Accepted",
203 => "Non-Authoritative Information",
204 => "No Content",
205 => "Reset Content",
206 => "Partial Content",
207 => "Multi-Status",
300 => "Multiple Choices",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
305 => "Use Proxy",
306 => "Switch Proxy",
307 => "Temporary Redirect",
400 => "Bad Request",
401 => "Unauthorized",
402 => "Payment Required",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
406 => "Not Acceptable",
407 => "Proxy Authentication Required",
408 => "Request Timeout",
409 => "Conflict",
410 => "Gone",
411 => "Length Required",
412 => "Precondition Failed",
413 => "Request Entity Too Large",
414 => "Request-URI Too Long",
415 => "Unsupported Media Type",
416 => "Requested Range Not Satisfiable",
417 => "Expectation Failed",
418 => "I'm a teapot",
421 => "There are too many connections from your internet address",
422 => "Unprocessable Entity",
423 => "Locked",
424 => "Failed Dependency",
425 => "Unordered Collection",
426 => "Upgrade Required",
449 => "Retry With",
450 => "Blocked by Windows Parental Controls",
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Timeout",
505 => "HTTP Version Not Supported",
506 => "Variant Also Negotiates",
507 => "Insufficient Storage",
509 => "Bandwidth Limit Exceeded",
510 => "Not Extended",
530 => "User access denied"
}.freeze
end
+
end
end
diff --git a/tasks/docs.rake b/tasks/docs.rake
index 5a91f74..85f460e 100644
--- a/tasks/docs.rake
+++ b/tasks/docs.rake
@@ -1,109 +1,109 @@
begin
require 'yard'
require 'haml'
desc 'Build all documentation'
task :docs => %w[docs:static docs:api]
task :doc => :docs # alias for docs
CLEAN.include 'docs/build'
desc 'Build API documentation (docs/api)'
task 'docs:api' => ['docs/build/.git'] do
- sh("yardoc -o docs/build/api lib/**/*.rb")
+ sh("yardoc -o docs/build/api -")
end
desc 'Build static documentation (docs)'
task 'docs:static' => ['docs/build/.git'] do
require 'pathname'
require 'fileutils'
require 'rubygems'
require 'haml'
module Highlighting
def highlight(language, text)
code = ""
IO.popen("pygmentize -l#{language} -fhtml", "w+") do |io|
io.write(text)
io.close_write
code = io.read
end
code
end
end
module Haml::Filters::Code
include Highlighting
include Haml::Filters::Base
def render(text)
highlight('ruby', text)
end
end
module Haml::Filters::Bash
include Highlighting
include Haml::Filters::Base
def render(text)
highlight('bash', text)
end
end
class GeneratorContext
end
layout = Haml::Engine.new(File.read("docs/layout.html.haml"))
FileList["docs/{stylesheets,images}/*"].each do |resource|
path = Pathname(resource)
relative_path = path.relative_path_from(Pathname("docs"))
build_path = Pathname("docs/build") + relative_path
FileUtils.mkdir_p(build_path.parent.to_s)
FileUtils.copy(resource, build_path)
end
FileList["docs/**/*.haml"].exclude("docs/layout.html.haml").each do |entry|
path = Pathname(entry)
relative_path = path.relative_path_from(Pathname("docs"))
build_path = Pathname("docs/build") + relative_path.parent + path.basename.sub(/\.haml$/, '')
FileUtils.mkdir_p(build_path.dirname)
File.open(build_path, "w") do |file|
context = GeneratorContext.new
content = ""
Dir.chdir(path.dirname) do
content = Haml::Engine.new(File.read(path.basename)).render(context)
end
puts "Writing: #{build_path.relative_path_from(Pathname("build"))}"
file.write build_path.extname == ".html" ? layout.render(context, :content => content) : content
end
end
end
# GITHUB PAGES ===============================================================
directory 'docs/build/'
desc 'Update gh-pages branch'
task :pages => ['docs/build/.git', :docs] do
rev = `git rev-parse --short HEAD`.strip
Dir.chdir 'docs/build' do
sh "git add ."
sh "git commit -m 'rebuild pages from #{rev}'" do |ok,res|
if ok
verbose { puts "gh-pages updated" }
sh "git push -q o HEAD:gh-pages"
end
end
end
end
# Update the pages/ directory clone
file 'docs/build/.git' => ['docs/build/', '.git/refs/heads/gh-pages'] do |f|
sh "cd docs/build && git init -q && git remote add o ../../.git" if !File.exist?(f.name)
sh "cd docs/build && git fetch -q o && git reset -q --hard o/gh-pages && touch ."
end
rescue LoadError
warn "** Yard and Haml are required for generating documentation. Try: gem install yard haml **"
end
|
bernerdschaefer/akephalos
|
052178bbf44600a1797b49d107a682332ec1dbf3
|
Document Akephalos::Server
|
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
index e259adc..ee4131c 100644
--- a/lib/akephalos/server.rb
+++ b/lib/akephalos/server.rb
@@ -1,25 +1,25 @@
# This file runs a JRuby DRb server, and is run by `akephalos --server`.
require "pathname"
require "drb/drb"
require "akephalos/client"
# In ruby-1.8.7 and later, the message for a NameError exception is lazily
# evaluated. There are, however, different implementations of this between ruby
-# and jrby, so we realize these messages when sending over DRb.
+# and jruby, so we realize these messages when sending over DRb.
class NameError::Message
def _dump
to_s
end
end
[Akephalos::Page, Akephalos::Node].each { |klass| klass.send(:include, DRbUndumped) }
module Akephalos
class Server
def self.start!(socket_file)
client = Client.new
DRb.start_service("drbunix://#{socket_file}", client)
DRb.thread.join
end
end
end
|
bernerdschaefer/akephalos
|
6722e940696a346ee0f339f5a41d7daab14778c3
|
Fix link to HtmlUnit in README
|
diff --git a/README.md b/README.md
index 36e2ebd..d0c9b54 100644
--- a/README.md
+++ b/README.md
@@ -1,55 +1,55 @@
# Akephalos
Akephalos is a full-stack headless browser for integration testing with
-Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.com),
+Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
## Installation
gem install akephalos
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
require 'akephalos'
Capybara.javascript_driver = :akephalos
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
## More
* [bin/akephalos](http://bernerdschaefer.github.com/akephalos/akephalos-bin.html)
allows you to start an interactive shell or DRb server, as well as perform
other maintenance features.
* [Filters](http://bernerdschaefer.github.com/akephalos/filters.html) allows
you to declare mock responses for external resources and services requested
by the browser.
## Resources
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
diff --git a/docs/index.html.haml b/docs/index.html.haml
index 573e0d6..952c576 100644
--- a/docs/index.html.haml
+++ b/docs/index.html.haml
@@ -1,67 +1,67 @@
%section
:markdown
Akephalos is a full-stack headless browser for integration testing with
- Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.com),
+ Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.net),
a GUI-less browser for the Java platform, but can be run on both JRuby and
MRI with no need for JRuby to be installed on the system.
%section
:markdown
## Installation
%aside
:bash
gem install akephalos
%section
:markdown
## Setup
Configuring akephalos is as simple as requiring it and setting Capybara's
javascript driver:
%aside
:code
require 'akephalos'
Capybara.javascript_driver = :akephalos
%section
:markdown
## Basic Usage
Akephalos provides a driver for Capybara, so using Akephalos is no
different than using Selenium or Rack::Test. For a full usage guide, check
out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
makes no assumptions about the testing framework being used, and works with
RSpec, Cucumber, and Test::Unit.
Here's some sample RSpec code:
%aside
:code
describe "Home Page" do
before { visit "/" }
context "searching" do
before do
fill_in "Search", :with => "akephalos"
click_button "Go"
end
it "returns results" { page.should have_css("#results") }
it "includes the search term" { page.should have_content("akephalos") }
end
end
%section
:markdown
## More
* [bin/akephalos](akephalos-bin.html) allows you to start an interactive
shell or DRb server, as well as perform other maintenance features.
* [Filters](filters.html) allows you to declare mock responses for
external resources and services requested by the browser.
## Resources
* [Source code](http://github.com/bernerdschaefer/akephalos) and
[issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
github.
|
bernerdschaefer/akephalos
|
13ed2e6a78d3605f674cf2f928dce0153981138d
|
Version bump for htmlunit-2.8
|
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index 87b6849..5ad5c2d 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.2.2"
+ VERSION = "0.2.3"
end
diff --git a/src/htmlunit/apache-mime4j-0.6.jar b/src/htmlunit/apache-mime4j-0.6.jar
new file mode 100644
index 0000000..1d2282c
Binary files /dev/null and b/src/htmlunit/apache-mime4j-0.6.jar differ
diff --git a/src/htmlunit/commons-httpclient-3.1.jar b/src/htmlunit/commons-httpclient-3.1.jar
deleted file mode 100644
index 7c59774..0000000
Binary files a/src/htmlunit/commons-httpclient-3.1.jar and /dev/null differ
diff --git a/src/htmlunit/htmlunit-2.7.jar b/src/htmlunit/htmlunit-2.7.jar
deleted file mode 100644
index 6cd0122..0000000
Binary files a/src/htmlunit/htmlunit-2.7.jar and /dev/null differ
diff --git a/src/htmlunit/htmlunit-2.8.jar b/src/htmlunit/htmlunit-2.8.jar
new file mode 100644
index 0000000..0c9b0f8
Binary files /dev/null and b/src/htmlunit/htmlunit-2.8.jar differ
diff --git a/src/htmlunit/htmlunit-core-js-2.7.jar b/src/htmlunit/htmlunit-core-js-2.8.jar
similarity index 89%
rename from src/htmlunit/htmlunit-core-js-2.7.jar
rename to src/htmlunit/htmlunit-core-js-2.8.jar
index 7d9cc00..a47a832 100644
Binary files a/src/htmlunit/htmlunit-core-js-2.7.jar and b/src/htmlunit/htmlunit-core-js-2.8.jar differ
diff --git a/src/htmlunit/httpclient-4.0.1.jar b/src/htmlunit/httpclient-4.0.1.jar
new file mode 100644
index 0000000..ad32285
Binary files /dev/null and b/src/htmlunit/httpclient-4.0.1.jar differ
diff --git a/src/htmlunit/httpcore-4.0.1.jar b/src/htmlunit/httpcore-4.0.1.jar
new file mode 100644
index 0000000..4aef35e
Binary files /dev/null and b/src/htmlunit/httpcore-4.0.1.jar differ
diff --git a/src/htmlunit/httpmime-4.0.1.jar b/src/htmlunit/httpmime-4.0.1.jar
new file mode 100644
index 0000000..85a0821
Binary files /dev/null and b/src/htmlunit/httpmime-4.0.1.jar differ
|
bernerdschaefer/akephalos
|
29912f763474ac34acb61caa50ccd281e0e1689c
|
VERSION 0.2.2
|
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index 92a7cf0..87b6849 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.2.1"
+ VERSION = "0.2.2"
end
|
bernerdschaefer/akephalos
|
6f8a68146adc01963299addd327dbb28d4d22842
|
Explicitly require 'pathname' in akephalos.rb
|
diff --git a/lib/akephalos.rb b/lib/akephalos.rb
index 7397cbd..c8048f3 100644
--- a/lib/akephalos.rb
+++ b/lib/akephalos.rb
@@ -1,18 +1,19 @@
# **Akephalos** is a cross-platform Ruby interface for *HtmlUnit*, a headless
# browser for the Java platform.
#
# The only requirement is that a Java runtime is available.
#
require 'java' if RUBY_PLATFORM == 'java'
+require 'pathname'
require 'capybara'
module Akephalos
BIN_DIR = Pathname(__FILE__).expand_path.dirname.parent + 'bin'
end
require 'akephalos/client'
require 'akephalos/capybara'
if Object.const_defined? :Cucumber
require 'akephalos/cucumber'
end
|
bernerdschaefer/akephalos
|
4d81487c1023088ec693b75539943d9f07a92f52
|
VERSION 0.2.1
|
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index d902caa..92a7cf0 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.2.0"
+ VERSION = "0.2.1"
end
|
bernerdschaefer/akephalos
|
775ddfacef44a6ff10babb33697f90c4c35d9dc9
|
Fix gemspec require_paths
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index f0f190b..9d41cd7 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
s.add_runtime_dependency "capybara", "~> 0.3.8"
if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
s.add_development_dependency "rspec", "1.3.0"
- s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
- s.require_path = %w(lib src)
- s.executables = %w(akephalos)
+ s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
+ s.require_paths = %w(lib src)
+ s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
afaaca88a02fb57be1b248ace2bb1597a8d39adb
|
VERSION 0.2
|
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index 248c467..d902caa 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.1.0"
+ VERSION = "0.2.0"
end
|
bernerdschaefer/akephalos
|
7597340acc09aa4fc58233f0a07f104bb754a997
|
Fix gemspec when bundling with jruby
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 2360855..f0f190b 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
s.add_runtime_dependency "capybara", "~> 0.3.8"
- if ENV["PLATFORM"] != "java"
+ if RUBY_PLATFORM != "java" && ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
s.add_development_dependency "rspec", "1.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_path = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
78320994882feb5ba62da9d24ca0b40aeb260cc8
|
Ignore Gemfile.lock
|
diff --git a/.gitignore b/.gitignore
index 5a40241..9f80dbc 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,8 @@
.bundle/
.rvmrc
.yardoc
+Gemfile.lock
burn
+docs/build
pkg
tags
-docs/build
|
bernerdschaefer/akephalos
|
6952f07cb931b284f0b8e86a92224375c64ae1e6
|
Fix rspec dependency in gemspec
|
diff --git a/akephalos.gemspec b/akephalos.gemspec
index 45f8b3f..e8fa80b 100644
--- a/akephalos.gemspec
+++ b/akephalos.gemspec
@@ -1,32 +1,32 @@
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "akephalos/version"
Gem::Specification.new do |s|
s.name = "akephalos"
s.version = Akephalos::VERSION
s.platform = ENV["PLATFORM"] || "ruby"
s.authors = ["Bernerd Schaefer"]
s.email = "[email protected]"
s.homepage = "http://bernerdschaefer.github.com/akephalos"
s.summary = "Headless Browser for Integration Testing with Capybara"
s.description = s.summary
s.required_rubygems_version = ">= 1.3.6"
s.rubyforge_project = "akephalos"
s.add_runtime_dependency "capybara", "0.3.8"
if ENV["PLATFORM"] != "java"
s.add_runtime_dependency "jruby-jars"
end
s.add_development_dependency "sinatra"
- s.add_development_dependency "rspec", "1.30"
+ s.add_development_dependency "rspec", "1.3.0"
s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
s.require_path = %w(lib src)
s.executables = %w(akephalos)
end
|
bernerdschaefer/akephalos
|
30db0f6df52a719dd26fc6237e68f60810ee694d
|
Add *.gem to rakefile clean task
|
diff --git a/Rakefile b/Rakefile
index 1958141..c68a3d4 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,39 +1,41 @@
require 'rubygems'
require 'rake'
require 'rake/clean'
JAVA = RUBY_PLATFORM == "java"
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "akephalos/version"
+CLEAN.include "*.gem"
+
task :build do
system "gem build akephalos.gemspec"
end
task "build:java" do
system "export PLATFORM=java && gem build akephalos.gemspec"
end
task "build:all" => ['build', 'build:java']
task :install => (JAVA ? 'build:java' : 'build') do
gemfile = "akephalos-#{Akephalos::VERSION}#{"-java" if JAVA}.gem"
system "gem install #{gemfile}"
end
task :release => :build_all do
puts "Tagging #{Akephalos::VERSION}..."
system "git tag -a #{Akephalos::VERSION} -m 'Tagging #{Akephalos::VERSION}'"
puts "Pushing to Github..."
system "git push --tags"
puts "Pushing to Gemcutter..."
["", "-java"].each do |platform|
system "gem push akephalos-#{Akephalos::VERSION}#{platform}.gem"
end
end
load 'tasks/docs.rake'
load 'tasks/spec.rake'
task :default => :spec
|
bernerdschaefer/akephalos
|
e24833f16ff9ee59b10eed691ef49d2bbb7ea081
|
Use gemspec for Gemfile dependencies
|
diff --git a/Gemfile b/Gemfile
index 02f32ec..e0a7662 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,4 +1 @@
-gem "jruby-jars" if RUBY_PLATFORM != "java"
-gem "capybara", "0.3.8"
-gem "rspec", "1.3.0"
-gem "sinatra"
+gemspec
|
bernerdschaefer/akephalos
|
381838a8aa928de94fcc6ef559a76f67279bd2c5
|
VERSION 0.1
|
diff --git a/Rakefile b/Rakefile
index dfba25f..1958141 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,39 +1,39 @@
require 'rubygems'
require 'rake'
require 'rake/clean'
JAVA = RUBY_PLATFORM == "java"
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "akephalos/version"
task :build do
system "gem build akephalos.gemspec"
end
task "build:java" do
system "export PLATFORM=java && gem build akephalos.gemspec"
end
-task :build_all => ['build', 'build:java']
+task "build:all" => ['build', 'build:java']
task :install => (JAVA ? 'build:java' : 'build') do
gemfile = "akephalos-#{Akephalos::VERSION}#{"-java" if JAVA}.gem"
system "gem install #{gemfile}"
end
task :release => :build_all do
puts "Tagging #{Akephalos::VERSION}..."
system "git tag -a #{Akephalos::VERSION} -m 'Tagging #{Akephalos::VERSION}'"
puts "Pushing to Github..."
system "git push --tags"
puts "Pushing to Gemcutter..."
["", "-java"].each do |platform|
system "gem push akephalos-#{Akephalos::VERSION}#{platform}.gem"
end
end
load 'tasks/docs.rake'
load 'tasks/spec.rake'
task :default => :spec
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
index f7f26e6..248c467 100644
--- a/lib/akephalos/version.rb
+++ b/lib/akephalos/version.rb
@@ -1,3 +1,3 @@
module Akephalos #:nodoc
- VERSION = "0.0.5"
+ VERSION = "0.1.0"
end
|
bernerdschaefer/akephalos
|
6082c618f8a50ade81c5ec78623ca6aa54038e39
|
Disable history tracking in HtmlUnit
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..5a40241
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,7 @@
+.bundle/
+.rvmrc
+.yardoc
+burn
+pkg
+tags
+docs/build
diff --git a/.watch b/.watch
new file mode 100644
index 0000000..50764ff
--- /dev/null
+++ b/.watch
@@ -0,0 +1,4 @@
+$server = fork { Dir.chdir("docs/build") { system("python -m SimpleHTTPServer") } } unless $server
+watch('lib/.*') { system("rake docs:api") }
+watch('docs/.*.haml') { system("rake docs:static") }
+#watch('docs/.*.css') { system("rake docs:static") }
diff --git a/Gemfile b/Gemfile
new file mode 100644
index 0000000..02f32ec
--- /dev/null
+++ b/Gemfile
@@ -0,0 +1,4 @@
+gem "jruby-jars" if RUBY_PLATFORM != "java"
+gem "capybara", "0.3.8"
+gem "rspec", "1.3.0"
+gem "sinatra"
diff --git a/MIT_LICENSE b/MIT_LICENSE
new file mode 100644
index 0000000..87a0e51
--- /dev/null
+++ b/MIT_LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2010 Bernerd Schaefer
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..36e2ebd
--- /dev/null
+++ b/README.md
@@ -0,0 +1,55 @@
+# Akephalos
+Akephalos is a full-stack headless browser for integration testing with
+Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.com),
+a GUI-less browser for the Java platform, but can be run on both JRuby and
+MRI with no need for JRuby to be installed on the system.
+
+## Installation
+
+ gem install akephalos
+
+## Setup
+
+Configuring akephalos is as simple as requiring it and setting Capybara's
+javascript driver:
+
+ require 'akephalos'
+ Capybara.javascript_driver = :akephalos
+
+## Basic Usage
+
+Akephalos provides a driver for Capybara, so using Akephalos is no
+different than using Selenium or Rack::Test. For a full usage guide, check
+out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
+makes no assumptions about the testing framework being used, and works with
+RSpec, Cucumber, and Test::Unit.
+
+Here's some sample RSpec code:
+
+ describe "Home Page" do
+ before { visit "/" }
+ context "searching" do
+ before do
+ fill_in "Search", :with => "akephalos"
+ click_button "Go"
+ end
+ it "returns results" { page.should have_css("#results") }
+ it "includes the search term" { page.should have_content("akephalos") }
+ end
+ end
+
+## More
+
+* [bin/akephalos](http://bernerdschaefer.github.com/akephalos/akephalos-bin.html)
+ allows you to start an interactive shell or DRb server, as well as perform
+ other maintenance features.
+
+* [Filters](http://bernerdschaefer.github.com/akephalos/filters.html) allows
+ you to declare mock responses for external resources and services requested
+ by the browser.
+
+## Resources
+
+* [Source code](http://github.com/bernerdschaefer/akephalos) and
+ [issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
+ github.
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..dfba25f
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,39 @@
+require 'rubygems'
+require 'rake'
+require 'rake/clean'
+
+JAVA = RUBY_PLATFORM == "java"
+
+$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
+require "akephalos/version"
+
+task :build do
+ system "gem build akephalos.gemspec"
+end
+
+task "build:java" do
+ system "export PLATFORM=java && gem build akephalos.gemspec"
+end
+
+task :build_all => ['build', 'build:java']
+
+task :install => (JAVA ? 'build:java' : 'build') do
+ gemfile = "akephalos-#{Akephalos::VERSION}#{"-java" if JAVA}.gem"
+ system "gem install #{gemfile}"
+end
+
+task :release => :build_all do
+ puts "Tagging #{Akephalos::VERSION}..."
+ system "git tag -a #{Akephalos::VERSION} -m 'Tagging #{Akephalos::VERSION}'"
+ puts "Pushing to Github..."
+ system "git push --tags"
+ puts "Pushing to Gemcutter..."
+ ["", "-java"].each do |platform|
+ system "gem push akephalos-#{Akephalos::VERSION}#{platform}.gem"
+ end
+end
+
+load 'tasks/docs.rake'
+load 'tasks/spec.rake'
+
+task :default => :spec
diff --git a/TODO.txt b/TODO.txt
new file mode 100644
index 0000000..e8b8a40
--- /dev/null
+++ b/TODO.txt
@@ -0,0 +1,33 @@
+0.0.5
+=======================================================================================
+ * Upgrade to htmlunit-2.7
+ * Fix DRb recycled object errors
+ * Define NativeException on ruby side so that uncaught exceptions are displayed with
+ a proper backtrace.
+ * Add Akephalos.filter() for enabling FakeWeb style request/response mocking in the
+ HtmlUnit browser.
+
+0.0.4
+=======================================================================================
+ - Update to jruby 1.5
+ - bin/akephalos for interactive mode
+ - use internally managed java threading instead of capybara's own wait methods
+
+0.0.3
+=======================================================================================
+
+ - Update for compatibility with capybara 0.3.8
+
+0.0.2 - 10 May 2010
+=======================================================================================
+
+ - Ensure users cannot accidently call non-existant methods on DRb objects
+ - Refactor akephalos classes to expose HTMLUnit behavior, instead of shipping
+ objects directly to remote process.
+
+
+0.0.1 - 03 May 2010
+=======================================================================================
+ - DRb server starts automatically when needed
+ - DRb objects are undumped, and references are kept on the server
+ - All capybara provided specs pass.
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..bbdeab6
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+0.0.5
diff --git a/akephalos.gemspec b/akephalos.gemspec
new file mode 100644
index 0000000..45f8b3f
--- /dev/null
+++ b/akephalos.gemspec
@@ -0,0 +1,32 @@
+# -*- encoding: utf-8 -*-
+lib = File.expand_path('../lib/', __FILE__)
+$:.unshift lib unless $:.include?(lib)
+
+require "akephalos/version"
+
+Gem::Specification.new do |s|
+ s.name = "akephalos"
+ s.version = Akephalos::VERSION
+ s.platform = ENV["PLATFORM"] || "ruby"
+ s.authors = ["Bernerd Schaefer"]
+ s.email = "[email protected]"
+ s.homepage = "http://bernerdschaefer.github.com/akephalos"
+ s.summary = "Headless Browser for Integration Testing with Capybara"
+ s.description = s.summary
+
+ s.required_rubygems_version = ">= 1.3.6"
+ s.rubyforge_project = "akephalos"
+
+ s.add_runtime_dependency "capybara", "0.3.8"
+
+ if ENV["PLATFORM"] != "java"
+ s.add_runtime_dependency "jruby-jars"
+ end
+
+ s.add_development_dependency "sinatra"
+ s.add_development_dependency "rspec", "1.30"
+
+ s.files = Dir.glob("lib/**/*.rb") + Dir.glob("src/**/*.jar") + %w(README.md MIT_LICENSE)
+ s.require_path = %w(lib src)
+ s.executables = %w(akephalos)
+end
diff --git a/bin/akephalos b/bin/akephalos
new file mode 100755
index 0000000..89f65db
--- /dev/null
+++ b/bin/akephalos
@@ -0,0 +1,87 @@
+#!/usr/bin/env ruby
+# vim:set filetype=ruby:
+
+require "pathname"
+require "optparse"
+
+options = { :interactive => false }
+
+parser = OptionParser.new do |opts|
+ opts.banner = "Usage: akephalos [--interactive, --use-htmlunit-snapshot] | [--server] <socket_file>"
+ opts.on("-s", "--server", "Run in server mode (default)")
+ opts.on("-i", "--interactive", "Run in interactive mode") { options[:interactive] = true }
+ opts.on("--use-htmlunit-snapshot", "Use the snapshot of htmlunit") { options[:use_htmlunit_snapshot] = true }
+
+ opts.on_tail("-h", "--help", "Show this message") { puts opts; exit }
+end
+parser.parse!
+
+root = Pathname(__FILE__).expand_path.dirname.parent
+lib = root + 'lib'
+src = root + 'src'
+
+case
+when options[:use_htmlunit_snapshot]
+ require "fileutils"
+
+ FileUtils.mkdir_p("vendor/htmlunit")
+ Dir["vendor/htmlunit/*.jar"].each { |jar| File.unlink(jar) }
+
+ Dir.chdir("vendor") do
+ $stdout.print "Downloading latest snapshot... "
+ $stdout.flush
+ %x[curl -O http://build.canoo.com/htmlunit/artifacts/htmlunit-2.8-SNAPSHOT-with-dependencies.zip &> /dev/null]
+ puts "done"
+
+ $stdout.print "Extracting dependencies... "
+ $stdout.flush
+ %x[unzip -j -d htmlunit htmlunit-2.8-SNAPSHOT-with-dependencies.zip htmlunit-2.8-SNAPSHOT/lib htmlunit-2.8-SNAPSHOT/lib/* &> /dev/null]
+ puts "done"
+
+ File.unlink "htmlunit-2.8-SNAPSHOT-with-dependencies.zip"
+ end
+
+ $stdout.puts "="*40
+ $stdout.puts "The latest HtmlUnit snapshot has been extracted to vendor/htmlunit!"
+when options[:interactive]
+ $:.unshift('vendor', lib, src)
+ require 'rubygems'
+ require 'akephalos'
+ require 'akephalos/console'
+ Akephalos::Console.start
+else
+ unless socket_file = ARGV[0]
+ puts parser.help
+ exit
+ end
+
+ if RUBY_PLATFORM == "java"
+ $:.unshift("vendor", lib, src)
+ require 'akephalos/server'
+ Akephalos::Server.start!(socket_file)
+ else
+ require 'rubygems'
+ require 'jruby-jars'
+
+ jruby = JRubyJars.core_jar_path
+ jruby_stdlib = JRubyJars.stdlib_jar_path
+
+ java_args = [
+ "-Xmx128M",
+ "-cp", [JRubyJars.core_jar_path, JRubyJars.stdlib_jar_path].join(":"),
+ "org.jruby.Main"
+ ]
+ ruby_args = [
+ "-I", "vendor:#{lib}:#{src}",
+ "-r", "akephalos/server",
+ "-e", "Akephalos::Server.start!(#{socket_file.inspect})"
+ ]
+
+ # Bundler sets ENV["RUBYOPT"] to automatically load bundler/setup.rb, but
+ # since the akephalos server doesn't have any gem dependencies and is
+ # always executed with the same context, we clear RUBYOPT before running
+ # exec.
+ ENV["RUBYOPT"] = ""
+ exec("java", *(java_args + ruby_args))
+ end
+end
diff --git a/docs/akephalos-bin.html.haml b/docs/akephalos-bin.html.haml
new file mode 100644
index 0000000..02364e0
--- /dev/null
+++ b/docs/akephalos-bin.html.haml
@@ -0,0 +1,49 @@
+- @title = 'bin/akephalos'
+%section
+ :markdown
+ ## bin/akephalos
+
+ The bundled `akephalos` binary provides a command line interface to a few
+ useful features.
+
+ ### `akephalos --interactive`
+
+ Running akephalos in interactive mode gives you an IRB context for
+ interacting with your site just as you would in your tests:
+
+%aside
+ :code
+ # akephalos --interactive
+ Capybara.app_host # => "http://localhost:3000"
+ page.visit "/"
+ page.fill_in "Search", :with => "akephalos"
+ page.click_button "Go"
+ page.has_css?("#search_results") # => true
+
+%section
+ :markdown
+ ### `akephalos --use-htmlunit-snapshot`
+
+ This will instruct akephalos to use the latest development snapshot of
+ HtmlUnit as found on it's [Cruise Control
+ server](http://build.canoo.com/htmlunit/). HtmlUnit and its dependencies
+ will be unpacked into vendor/htmlunit in the current working directory.
+
+ This is what the output looks like:
+
+%aside
+ :bash
+ > bin/akephalos --use-htmlunit-snapshot
+ Downloading latest snapshot... done
+ Extracting dependencies... done
+ ========================================
+ The latest HtmlUnit snapshot has been extracted to vendor/htmlunit!
+
+%section
+ :markdown
+ Once HtmlUnit has been extracted, Akephalos will automatically detect the
+ vendored version and use it instead of the bundled version.
+
+ ### `akephalos --server <socket_file>`
+
+ Akephalos uses this command internally to start a JRuby DRb server using the provided socket file.
diff --git a/docs/filters.html.haml b/docs/filters.html.haml
new file mode 100644
index 0000000..ba85a18
--- /dev/null
+++ b/docs/filters.html.haml
@@ -0,0 +1,88 @@
+- @title = 'Filters'
+%section
+ :markdown
+ ## Filters
+
+ Akephalos allows you to filter requests originating from the browser and
+ return mock responses. This will let you easily filter requests for
+ external resources when running your tests, such as Facebook's API and
+ Google Analytics.
+
+ Configuring filters in akephalos should be familiar to anyone who has used
+ FakeWeb or a similar library. The simplest filter requires only an
+ <abbr>HTTP</abbr> method (`:get`, `:post`, `:put`, `:delete`, `:any`) and a
+ string or regex to match against.
+
+%aside
+ :code
+ Akephalos.filter(:get, "http://www.google.com")
+ Akephalos.filter(:any, %r{^http://(api\.)?twitter\.com/.*$})
+
+%section
+ :markdown
+ By default, all filtered requests will return an empty body with a 200
+ status code. You can change this by passing additional options to your
+ filter call.
+
+%aside
+ :code
+ Akephalos.filter(:get, "http://google.com/missing",
+ :status => 404, :body => "... <h1>Not Found</h1> ...")
+
+ Akephalos.filter(:post, "http://my-api.com/resource.xml",
+ :status => 201, :headers => {
+ "Content-Type" => "application/xml",
+ "Location" => "http://my-api.com/resources/1.xml" },
+ :body => {:id => 100}.to_xml)
+
+%section
+ :markdown
+ And that's really all there is to it! It should be fairly trivial to set up
+ filters for the external resources you need to fake. For reference,
+ however, here's what we ended up using for our external sources.
+
+ ### Google Analytics
+
+ Google Analytics code is passively applied based on HTML comments, so
+ simply returning an empty response body is enough to disable it without
+ errors.
+
+%aside
+ :code
+ Akephalos.filter(:get, "http://www.google-analytics.com/ga.js",
+ :headers => {"Content-Type" => "application/javascript"})
+
+%section
+ :markdown
+ ### Facebook Connect
+
+ When you enable Facebook Connect on your page, the FeatureLoader is
+ requested, and then additional resources are loaded when you call
+ FB_RequireFeatures. We can therefore return an empty function from our
+ filter to disable all Facebook Connect code.
+
+%aside
+ :code
+ Akephalos.filter(:get, "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php",
+ :headers => {"Content-Type" => "application/javascript"},
+ :body => "window.FB_RequireFeatures = function() {};")
+
+%section
+ :markdown
+ ### Google Maps
+
+ Google Maps requires the most extensive amount of API definitions of the
+ three, but these few lines cover everything we've encountered so far.
+
+%aside
+ :code
+ Akephalos.filter(:get, "http://maps.google.com/maps/api/js?sensor=false",
+ :headers => {"Content-Type" => "application/javascript"},
+ :body => "window.google = {
+ maps: {
+ LatLng: function(){},
+ Map: function(){},
+ Marker: function(){},
+ MapTypeId: {ROADMAP:1}
+ }
+ };")
diff --git a/docs/index.html.haml b/docs/index.html.haml
new file mode 100644
index 0000000..573e0d6
--- /dev/null
+++ b/docs/index.html.haml
@@ -0,0 +1,67 @@
+%section
+ :markdown
+ Akephalos is a full-stack headless browser for integration testing with
+ Capybara. It is built on top of [HtmlUnit](http://htmlunit.sourceforge.com),
+ a GUI-less browser for the Java platform, but can be run on both JRuby and
+ MRI with no need for JRuby to be installed on the system.
+
+%section
+ :markdown
+ ## Installation
+%aside
+ :bash
+ gem install akephalos
+
+%section
+ :markdown
+ ## Setup
+
+ Configuring akephalos is as simple as requiring it and setting Capybara's
+ javascript driver:
+
+%aside
+ :code
+ require 'akephalos'
+ Capybara.javascript_driver = :akephalos
+
+%section
+ :markdown
+ ## Basic Usage
+
+ Akephalos provides a driver for Capybara, so using Akephalos is no
+ different than using Selenium or Rack::Test. For a full usage guide, check
+ out Capybara's DSL [documentation](http://github.com/jnicklas/capybara). It
+ makes no assumptions about the testing framework being used, and works with
+ RSpec, Cucumber, and Test::Unit.
+
+ Here's some sample RSpec code:
+
+%aside
+ :code
+ describe "Home Page" do
+ before { visit "/" }
+ context "searching" do
+ before do
+ fill_in "Search", :with => "akephalos"
+ click_button "Go"
+ end
+ it "returns results" { page.should have_css("#results") }
+ it "includes the search term" { page.should have_content("akephalos") }
+ end
+ end
+
+%section
+ :markdown
+ ## More
+
+ * [bin/akephalos](akephalos-bin.html) allows you to start an interactive
+ shell or DRb server, as well as perform other maintenance features.
+
+ * [Filters](filters.html) allows you to declare mock responses for
+ external resources and services requested by the browser.
+
+ ## Resources
+
+ * [Source code](http://github.com/bernerdschaefer/akephalos) and
+ [issues](http://github.com/bernerdschaefer/akephalos/issues) are hosted on
+ github.
diff --git a/docs/layout.html.haml b/docs/layout.html.haml
new file mode 100644
index 0000000..7a51baa
--- /dev/null
+++ b/docs/layout.html.haml
@@ -0,0 +1,21 @@
+!!!
+%html
+ %head
+ %meta{ :content => "text/html; charset=utf-8", "http-equiv" => "content-type" }
+ %title
+ akephalos
+ = ":: #{@title}" if @title
+ %meta(name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;")/
+ %link(href="stylesheets/screen.css" rel="stylesheet" type="text/css" media="screen" charset="utf-8")/
+ %link(rel="stylesheet" type="text/css" href="stylesheets/iphone.css" media="only screen and (max-width: 480px)")/
+ %body
+ %header
+ %h1
+ %a{ :href => "/akephalos" }
+ akephalos
+ %article
+ = content
+
+ %footer
+ %p
+ © 2010 · Bernerd Schaefer
diff --git a/docs/stylesheets/iphone.css b/docs/stylesheets/iphone.css
new file mode 100644
index 0000000..964c482
--- /dev/null
+++ b/docs/stylesheets/iphone.css
@@ -0,0 +1,9 @@
+body { padding: 0; }
+header { width: 100%; }
+header p { margin: 1em 1em; color: #777; font-style: italic; }
+article section { width: auto; padding: 0 1em; }
+time { position: relative; left: 0; float: left; margin-right: 1em; }
+aside { width: 100%; min-width: 0; margin: 0; padding: 1em 0; left: 0 }
+aside pre { margin: 0 1.5em; }
+footer { padding: 0; left: 0; text-indent: 0; text-align: center }
+pre { white-space: pre-wrap; word-break: break-all; text-wrap: unrestricted }
diff --git a/docs/stylesheets/screen.css b/docs/stylesheets/screen.css
new file mode 100644
index 0000000..3fbae7c
--- /dev/null
+++ b/docs/stylesheets/screen.css
@@ -0,0 +1,89 @@
+body { color: #111; font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, Georgia, FreeSerif, serif; line-height: 1.5em; margin: 0; padding: 40px 0 0 80px; }
+a { color: #44b }
+a:visited { color: #446 }
+abbr { font-size: 0.8em; border-bottom: 1px dotted #999; }
+header { background-color: #fff; display: block; width: 500px; margin-bottom: 20px }
+header h1 { background-color: #0E0826; margin: 0; font-weight: normal; line-height: 2em; text-align: center; font-style: italic; }
+header h1 a { color: #eee; display: block; text-decoration: none }
+header h1 a:visited { color: #eee; }
+header p { color: #777; }
+footer { display: block; color: #99a; line-height: 4em; font-size: 10px; width: 100%; position: relative; left: -80px; text-indent: -80px; padding-left: 80px; text-align: center; font-family: "Lucida Grande", Helvetica, sans-serif; font-weight: bold; margin-top: 20px }
+pre, tt, code, kbd { font-family: Monaco, Consolas, 'Lucida Console', monospace; font-size: 0.7em; }
+footer p { margin: 0 }
+article { background-color: #fff; display: block; line-height: 1.8em }
+article h1 a { color: #111; text-decoration: none }
+article section { display: block; width: 500px; }
+article section h2 { font-size: 1.4em }
+sup { margin: 0 0 0 2px; }
+section.footnotes { font-size: 0.8em }
+time { background-color: #b44; color: #fff; display: block; font: 8px "Lucida Grande", Helvetica, sans-serif; width: 30px; padding: 4px; -webkit-border-radius: 4px; text-align: center; position: absolute; left: 25px; }
+time .date { font-size: 16px; display: block }
+time .month { text-transform: uppercase; font-weight: bold }
+section h1 { line-height: 38px; margin: 0; font-size: 24px; }
+aside { display: block; background-color: rgb(245, 245, 255); border: 1px solid #dde; border-right: 0; border-left: 0; padding: 20px 0 20px 80px; margin-right: 0; min-width: 500px; position: relative; right: 0; width: 100%; left: -80px; line-height: 1.2em }
+
+/*---------------------- Syntax Highlighting -----------------------------*/
+td.linenos { background-color: #f0f0f0; padding-right: 10px; }
+span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }
+body .hll { background-color: #ffffcc }
+body .c { color: #408080; font-style: italic } /* Comment */
+/*body .err { border: 1px solid #FF0000 } /* Error */
+body .k { color: #954121 } /* Keyword */
+body .o { color: #666666 } /* Operator */
+body .cm { color: #408080; font-style: italic } /* Comment.Multiline */
+body .cp { color: #BC7A00 } /* Comment.Preproc */
+body .c1 { color: #408080; font-style: italic } /* Comment.Single */
+body .cs { color: #408080; font-style: italic } /* Comment.Special */
+body .gd { color: #A00000 } /* Generic.Deleted */
+body .ge { font-style: italic } /* Generic.Emph */
+body .gr { color: #FF0000 } /* Generic.Error */
+body .gh { color: #000080; font-weight: bold } /* Generic.Heading */
+body .gi { color: #00A000 } /* Generic.Inserted */
+body .go { color: #808080 } /* Generic.Output */
+body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
+body .gs { font-weight: bold } /* Generic.Strong */
+body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
+body .gt { color: #0040D0 } /* Generic.Traceback */
+body .kc { color: #954121 } /* Keyword.Constant */
+body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */
+body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */
+body .kp { color: #954121 } /* Keyword.Pseudo */
+body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */
+body .kt { color: #B00040 } /* Keyword.Type */
+body .m { color: #666666 } /* Literal.Number */
+body .s { color: #219161 } /* Literal.String */
+body .na { color: #7D9029 } /* Name.Attribute */
+body .nb { color: #954121 } /* Name.Builtin */
+body .nc { color: #0000FF; font-weight: bold } /* Name.Class */
+body .no { color: #880000 } /* Name.Constant */
+body .nd { color: #AA22FF } /* Name.Decorator */
+body .ni { color: #999999; font-weight: bold } /* Name.Entity */
+body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
+body .nf { color: #0000FF } /* Name.Function */
+body .nl { color: #A0A000 } /* Name.Label */
+body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
+body .nt { color: #954121; font-weight: bold } /* Name.Tag */
+body .nv { color: #19469D } /* Name.Variable */
+body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
+body .w { color: #bbbbbb } /* Text.Whitespace */
+body .mf { color: #666666 } /* Literal.Number.Float */
+body .mh { color: #666666 } /* Literal.Number.Hex */
+body .mi { color: #666666 } /* Literal.Number.Integer */
+body .mo { color: #666666 } /* Literal.Number.Oct */
+body .sb { color: #219161 } /* Literal.String.Backtick */
+body .sc { color: #219161 } /* Literal.String.Char */
+body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */
+body .s2 { color: #219161 } /* Literal.String.Double */
+body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
+body .sh { color: #219161 } /* Literal.String.Heredoc */
+body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
+body .sx { color: #954121 } /* Literal.String.Other */
+body .sr { color: #BB6688 } /* Literal.String.Regex */
+body .s1 { color: #219161 } /* Literal.String.Single */
+body .ss { color: #19469D } /* Literal.String.Symbol */
+body .bp { color: #954121 } /* Name.Builtin.Pseudo */
+body .vc { color: #19469D } /* Name.Variable.Class */
+body .vg { color: #19469D } /* Name.Variable.Global */
+body .vi { color: #19469D } /* Name.Variable.Instance */
+body .il { color: #666666 } /* Literal.Number.Integer.Long */
+
diff --git a/lib/akephalos.rb b/lib/akephalos.rb
new file mode 100644
index 0000000..7397cbd
--- /dev/null
+++ b/lib/akephalos.rb
@@ -0,0 +1,18 @@
+# **Akephalos** is a cross-platform Ruby interface for *HtmlUnit*, a headless
+# browser for the Java platform.
+#
+# The only requirement is that a Java runtime is available.
+#
+require 'java' if RUBY_PLATFORM == 'java'
+require 'capybara'
+
+module Akephalos
+ BIN_DIR = Pathname(__FILE__).expand_path.dirname.parent + 'bin'
+end
+
+require 'akephalos/client'
+require 'akephalos/capybara'
+
+if Object.const_defined? :Cucumber
+ require 'akephalos/cucumber'
+end
diff --git a/lib/akephalos/capybara.rb b/lib/akephalos/capybara.rb
new file mode 100644
index 0000000..00c9274
--- /dev/null
+++ b/lib/akephalos/capybara.rb
@@ -0,0 +1,161 @@
+class Capybara::Driver::Akephalos < Capybara::Driver::Base
+
+ class Node < Capybara::Node
+
+ def [](name)
+ name = name.to_s
+ case name
+ when 'checked'
+ node.checked?
+ else
+ node[name.to_s]
+ end
+ end
+
+ def text
+ node.text
+ end
+
+ def value
+ if tag_name == "select" && self[:multiple]
+ node.selected_options.map { |option| option.text }
+ elsif tag_name == "select"
+ selected_option = node.selected_options.first
+ selected_option ? selected_option.text : nil
+ else
+ self[:value]
+ end
+ end
+
+ def set(value)
+ if tag_name == 'textarea'
+ node.value = value.to_s
+ elsif tag_name == 'input' and type == 'radio'
+ click
+ elsif tag_name == 'input' and type == 'checkbox'
+ if value != self['checked']
+ click
+ end
+ elsif tag_name == 'input'
+ node.value = value.to_s
+ end
+ end
+
+ def select(option)
+ result = node.select_option(option)
+
+ if result == nil
+ options = node.options.map(&:text).join(", ")
+ raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
+ else
+ result
+ end
+ end
+
+ def unselect(option)
+ unless self[:multiple]
+ raise Capybara::UnselectNotAllowed, "Cannot unselect option '#{option}' from single select box."
+ end
+
+ result = node.unselect_option(option)
+
+ if result == nil
+ options = node.options.map(&:text).join(", ")
+ raise Capybara::OptionNotFound, "No such option '#{option}' in this select box. Available options: #{options}"
+ else
+ result
+ end
+ end
+
+ def trigger(event)
+ node.fire_event(event.to_s)
+ end
+
+ def tag_name
+ node.tag_name
+ end
+
+ def visible?
+ node.visible?
+ end
+
+ def drag_to(element)
+ trigger('mousedown')
+ element.trigger('mousemove')
+ element.trigger('mouseup')
+ end
+
+ def click
+ node.click
+ end
+
+ private
+
+ def all_unfiltered(selector)
+ nodes = []
+ node.find(selector).each { |node| nodes << Node.new(driver, node) }
+ nodes
+ end
+
+ def type
+ node[:type]
+ end
+ end
+
+ attr_reader :app, :rack_server
+
+ def self.driver
+ @driver ||= Akephalos::Client.new
+ end
+
+ def initialize(app)
+ @app = app
+ @rack_server = Capybara::Server.new(@app)
+ @rack_server.boot if Capybara.run_server
+ end
+
+ def visit(path)
+ browser.visit(url(path))
+ end
+
+ def source
+ page.source
+ end
+
+ def body
+ page.modified_source
+ end
+
+ def current_url
+ page.current_url
+ end
+
+ def find(selector)
+ nodes = []
+ page.find(selector).each { |node| nodes << Node.new(self, node) }
+ nodes
+ end
+
+ def evaluate_script(script)
+ page.execute_script script
+ end
+
+ def page
+ browser.page
+ end
+
+ def browser
+ self.class.driver
+ end
+
+ def wait
+ false
+ end
+
+private
+
+ def url(path)
+ rack_server.url(path)
+ end
+
+end
diff --git a/lib/akephalos/client.rb b/lib/akephalos/client.rb
new file mode 100644
index 0000000..a8d3116
--- /dev/null
+++ b/lib/akephalos/client.rb
@@ -0,0 +1,61 @@
+require 'akephalos/configuration'
+
+if RUBY_PLATFORM != "java"
+ require 'akephalos/remote_client'
+ Akephalos::Client = Akephalos::RemoteClient
+else
+ require 'akephalos/htmlunit'
+ require 'akephalos/htmlunit/ext/http_method'
+
+ require 'akephalos/page'
+ require 'akephalos/node'
+
+ require 'akephalos/client/filter'
+ require 'akephalos/client/listener'
+
+ module Akephalos
+ class Client
+ java_import 'com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController'
+ java_import 'com.gargoylesoftware.htmlunit.SilentCssErrorHandler'
+
+ attr_reader :page
+
+ def initialize
+ @_client = java.util.concurrent.FutureTask.new do
+ client = WebClient.new
+
+ Filter.new(client)
+ client.addWebWindowListener(Listener.new(self))
+ client.setAjaxController(NicelyResynchronizingAjaxController.new)
+ client.setCssErrorHandler(SilentCssErrorHandler.new)
+
+ client
+ end
+ Thread.new { @_client.run }
+ end
+
+ def configuration=(config)
+ Akephalos.configuration = config
+ end
+
+ def visit(url)
+ client.getPage(url)
+ page
+ end
+
+ def page=(_page)
+ if @page != _page
+ @page = Page.new(_page)
+ end
+ @page
+ end
+
+ private
+ def client
+ @client ||= @_client.get.tap do |client|
+ client.getCurrentWindow.getHistory.ignoreNewPages_.set(true)
+ end
+ end
+ end
+ end
+end
diff --git a/lib/akephalos/client/filter.rb b/lib/akephalos/client/filter.rb
new file mode 100644
index 0000000..3cc1cb7
--- /dev/null
+++ b/lib/akephalos/client/filter.rb
@@ -0,0 +1,82 @@
+module Akephalos
+ class Client
+ class Filter < WebConnectionWrapper
+ java_import 'com.gargoylesoftware.htmlunit.util.NameValuePair'
+ java_import 'com.gargoylesoftware.htmlunit.WebResponseData'
+ java_import 'com.gargoylesoftware.htmlunit.WebResponseImpl'
+
+ def filter(request)
+ if filter = Akephalos.filters.find { |filter| request.http_method === filter[:method] && request.url.to_s =~ filter[:filter] }
+ start_time = Time.now
+ headers = filter[:headers].map { |name, value| NameValuePair.new(name.to_s, value.to_s) }
+ response = WebResponseData.new(filter[:body].to_s.to_java_bytes, filter[:status], HTTP_STATUS_CODES.fetch(filter[:status], "Unknown"), headers)
+ WebResponseImpl.new(response, request, Time.now - start_time)
+ end
+ end
+
+ def getResponse(request)
+ filter(request) || super
+ end
+
+ HTTP_STATUS_CODES = {
+ 100 => "Continue",
+ 101 => "Switching Protocols",
+ 102 => "Processing",
+ 200 => "OK",
+ 201 => "Created",
+ 202 => "Accepted",
+ 203 => "Non-Authoritative Information",
+ 204 => "No Content",
+ 205 => "Reset Content",
+ 206 => "Partial Content",
+ 207 => "Multi-Status",
+ 300 => "Multiple Choices",
+ 301 => "Moved Permanently",
+ 302 => "Found",
+ 303 => "See Other",
+ 304 => "Not Modified",
+ 305 => "Use Proxy",
+ 306 => "Switch Proxy",
+ 307 => "Temporary Redirect",
+ 400 => "Bad Request",
+ 401 => "Unauthorized",
+ 402 => "Payment Required",
+ 403 => "Forbidden",
+ 404 => "Not Found",
+ 405 => "Method Not Allowed",
+ 406 => "Not Acceptable",
+ 407 => "Proxy Authentication Required",
+ 408 => "Request Timeout",
+ 409 => "Conflict",
+ 410 => "Gone",
+ 411 => "Length Required",
+ 412 => "Precondition Failed",
+ 413 => "Request Entity Too Large",
+ 414 => "Request-URI Too Long",
+ 415 => "Unsupported Media Type",
+ 416 => "Requested Range Not Satisfiable",
+ 417 => "Expectation Failed",
+ 418 => "I'm a teapot",
+ 421 => "There are too many connections from your internet address",
+ 422 => "Unprocessable Entity",
+ 423 => "Locked",
+ 424 => "Failed Dependency",
+ 425 => "Unordered Collection",
+ 426 => "Upgrade Required",
+ 449 => "Retry With",
+ 450 => "Blocked by Windows Parental Controls",
+ 500 => "Internal Server Error",
+ 501 => "Not Implemented",
+ 502 => "Bad Gateway",
+ 503 => "Service Unavailable",
+ 504 => "Gateway Timeout",
+ 505 => "HTTP Version Not Supported",
+ 506 => "Variant Also Negotiates",
+ 507 => "Insufficient Storage",
+ 509 => "Bandwidth Limit Exceeded",
+ 510 => "Not Extended",
+ 530 => "User access denied"
+ }.freeze
+ end
+ end
+end
diff --git a/lib/akephalos/client/listener.rb b/lib/akephalos/client/listener.rb
new file mode 100644
index 0000000..b2fbdcc
--- /dev/null
+++ b/lib/akephalos/client/listener.rb
@@ -0,0 +1,18 @@
+module Akephalos
+ class Client
+ class Listener
+ include com.gargoylesoftware.htmlunit.WebWindowListener
+
+ def initialize(client)
+ @client = client
+ end
+
+ def webWindowClosed(event)
+ end
+
+ def webWindowContentChanged(event)
+ @client.page = event.getNewPage
+ end
+ end
+ end
+end
diff --git a/lib/akephalos/configuration.rb b/lib/akephalos/configuration.rb
new file mode 100644
index 0000000..b600c0d
--- /dev/null
+++ b/lib/akephalos/configuration.rb
@@ -0,0 +1,22 @@
+module Akephalos
+ def self.configuration
+ @configuration ||= {}
+ end
+
+ def self.configuration=(config)
+ @configuration = config
+ end
+
+ module Filters
+ def filters
+ configuration[:filters] ||= []
+ end
+
+ def filter(method, regex, options = {})
+ regex = Regexp.new(Regexp.escape(regex)) if regex.is_a?(String)
+ filters << {:method => method, :filter => regex, :status => 200, :body => "", :headers => {}}.merge!(options)
+ end
+ end
+
+ extend Filters
+end
diff --git a/lib/akephalos/console.rb b/lib/akephalos/console.rb
new file mode 100644
index 0000000..b33c7e0
--- /dev/null
+++ b/lib/akephalos/console.rb
@@ -0,0 +1,27 @@
+def session
+ Capybara.app_host = "http://localhost:3000"
+ @session ||= Capybara::Session.new(:Akephalos)
+end
+alias page session
+
+module Akephalos
+ class Console
+
+ def self.start
+ require 'irb'
+
+ begin
+ require 'irb/completion'
+ rescue Exception
+ # No readline available, proceed anyway.
+ end
+
+ if ::File.exists? ".irbrc"
+ ENV['IRBRC'] = ".irbrc"
+ end
+
+ IRB.start
+ end
+
+ end
+end
diff --git a/lib/akephalos/cucumber.rb b/lib/akephalos/cucumber.rb
new file mode 100644
index 0000000..6507532
--- /dev/null
+++ b/lib/akephalos/cucumber.rb
@@ -0,0 +1,6 @@
+require 'capybara/cucumber'
+
+Before('@akephalos') do
+ Capybara.current_driver = :akephalos
+end
+
diff --git a/lib/akephalos/htmlunit.rb b/lib/akephalos/htmlunit.rb
new file mode 100644
index 0000000..4fe1520
--- /dev/null
+++ b/lib/akephalos/htmlunit.rb
@@ -0,0 +1,27 @@
+require "pathname"
+require "java"
+
+dependency_directory = $:.detect { |path| Dir[File.join(path, 'htmlunit/htmlunit-*.jar')].any? }
+
+raise "Could not find htmlunit/htmlunit-VERSION.jar in load path:\n [ #{$:.join(",\n ")}\n ]" unless dependency_directory
+
+Dir[File.join(dependency_directory, "htmlunit/*.jar")].each do |jar|
+ require jar
+end
+
+java.lang.System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog")
+java.lang.System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "fatal")
+java.lang.System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true")
+
+java_import "com.gargoylesoftware.htmlunit.WebClient"
+java_import "com.gargoylesoftware.htmlunit.util.WebConnectionWrapper"
+java_import 'com.gargoylesoftware.htmlunit.HttpMethod'
+
+
+# Disable history tracking
+com.gargoylesoftware.htmlunit.History.field_reader :ignoreNewPages_
+
+# Run in Firefox compatibility mode
+com.gargoylesoftware.htmlunit.BrowserVersion.setDefault(
+ com.gargoylesoftware.htmlunit.BrowserVersion::FIREFOX_3
+)
diff --git a/lib/akephalos/htmlunit/ext/http_method.rb b/lib/akephalos/htmlunit/ext/http_method.rb
new file mode 100644
index 0000000..ed2d7cb
--- /dev/null
+++ b/lib/akephalos/htmlunit/ext/http_method.rb
@@ -0,0 +1,18 @@
+class HttpMethod
+ def ===(other)
+ case other
+ when HttpMethod
+ super
+ when :any
+ true
+ when :get
+ self == self.class::GET
+ when :post
+ self == self.class::POST
+ when :put
+ self == self.class::PUT
+ when :delete
+ self == self.class::DELETE
+ end
+ end
+end
diff --git a/lib/akephalos/node.rb b/lib/akephalos/node.rb
new file mode 100644
index 0000000..5eaac11
--- /dev/null
+++ b/lib/akephalos/node.rb
@@ -0,0 +1,73 @@
+module Akephalos
+ class Node
+ def initialize(node)
+ @nodes = []
+ @_node = node
+ end
+
+ def checked?
+ @_node.isChecked
+ end
+
+ def text
+ @_node.asText
+ end
+
+ def [](name)
+ @_node.hasAttribute(name.to_s) ? @_node.getAttribute(name.to_s) : nil
+ end
+
+ def value=(value)
+ case tag_name
+ when "textarea"
+ @_node.setText(value)
+ when "input"
+ @_node.setValueAttribute(value)
+ end
+ end
+
+ def select_option(option)
+ opt = @_node.getOptions.detect { |o| o.asText == option }
+
+ opt && opt.setSelected(true)
+ end
+
+ def unselect_option(option)
+ opt = @_node.getOptions.detect { |o| o.asText == option }
+
+ opt && opt.setSelected(false)
+ end
+
+ def options
+ @_node.getOptions.map { |node| Node.new(node) }
+ end
+
+ def selected_options
+ @_node.getSelectedOptions.map { |node| Node.new(node) }
+ end
+
+ def fire_event(name)
+ @_node.fireEvent(name)
+ end
+
+ def tag_name
+ @_node.getNodeName
+ end
+
+ def visible?
+ @_node.isDisplayed
+ end
+
+ def click
+ @_node.click
+ @_node.getPage.getEnclosingWindow.getJobManager.waitForJobs(1000)
+ @_node.getPage.getEnclosingWindow.getJobManager.waitForJobsStartingBefore(1000)
+ end
+
+ def find(selector)
+ nodes = @_node.getByXPath(selector).map { |node| Node.new(node) }
+ @nodes << nodes
+ nodes
+ end
+ end
+end
diff --git a/lib/akephalos/page.rb b/lib/akephalos/page.rb
new file mode 100644
index 0000000..050719b
--- /dev/null
+++ b/lib/akephalos/page.rb
@@ -0,0 +1,34 @@
+module Akephalos
+ class Page
+ def initialize(page)
+ @nodes = []
+ @_page = page
+ end
+
+ def find(selector)
+ nodes = @_page.getByXPath(selector).map { |node| Node.new(node) }
+ @nodes << nodes
+ nodes
+ end
+
+ def modified_source
+ @_page.asXml
+ end
+
+ def source
+ @_page.getWebResponse.getContentAsString
+ end
+
+ def current_url
+ @_page.getWebResponse.getRequestSettings.getUrl.toString
+ end
+
+ def execute_script(script)
+ @_page.executeJavaScript(script).getJavaScriptResult
+ end
+
+ def ==(other)
+ @_page == other
+ end
+ end
+end
diff --git a/lib/akephalos/remote_client.rb b/lib/akephalos/remote_client.rb
new file mode 100644
index 0000000..a346b61
--- /dev/null
+++ b/lib/akephalos/remote_client.rb
@@ -0,0 +1,57 @@
+require 'drb/drb'
+
+# We need to define our own NativeException class for the cases when a native
+# exception is raised by the JRuby DRb server.
+class NativeException < StandardError; end # :nodoc:
+
+module Akephalos
+ ##
+ # The +RemoteClient+ class provides an interface to an +Akephalos::Client+
+ # isntance on a remote DRb server.
+ #
+ # == Usage
+ # client = Akephalos::RemoteClient.new
+ # client.visit "http://www.oinopa.com"
+ # client.page.source # => "<!DOCTYPE html PUBLIC..."
+ class RemoteClient
+ @socket_file = "/tmp/akephalos.#{Process.pid}.sock"
+
+ ##
+ # Starts a remote akephalos server and returns the remote Akephalos::Client
+ # instance.
+ def self.new
+ start!
+ DRb.start_service
+ client = DRbObject.new_with_uri("drbunix://#{@socket_file}")
+ # We want to share our local configuration with the remote server
+ # process, so we share an undumped version of our configuration. This
+ # lets us continue to make changes locally and have them reflected in the
+ # remote process.
+ client.configuration = Akephalos.configuration.extend(DRbUndumped)
+ client
+ end
+
+ ##
+ # Start a remote server process, returning when it is available for use.
+ def self.start!
+ remote_client = fork do
+ exec("#{Akephalos::BIN_DIR + 'akephalos'} #{@socket_file}")
+ end
+
+ # Set up a monitor thread to detect if the forked server exits
+ # prematurely.
+ server_monitor = Thread.new { Thread.current[:exited] = Process.wait }
+
+ # Wait for the server to be accessible on the socket we specified.
+ until File.exists?(@socket_file)
+ exit!(1) if server_monitor[:exited]
+ sleep 1
+ end
+ server_monitor.kill
+
+ # Ensure that the remote server shuts down gracefully when we are
+ # finished.
+ at_exit { Process.kill(:INT, remote_client); File.unlink(@socket_file) }
+ end
+ end
+end
diff --git a/lib/akephalos/server.rb b/lib/akephalos/server.rb
new file mode 100644
index 0000000..e259adc
--- /dev/null
+++ b/lib/akephalos/server.rb
@@ -0,0 +1,25 @@
+# This file runs a JRuby DRb server, and is run by `akephalos --server`.
+require "pathname"
+require "drb/drb"
+require "akephalos/client"
+
+# In ruby-1.8.7 and later, the message for a NameError exception is lazily
+# evaluated. There are, however, different implementations of this between ruby
+# and jrby, so we realize these messages when sending over DRb.
+class NameError::Message
+ def _dump
+ to_s
+ end
+end
+
+[Akephalos::Page, Akephalos::Node].each { |klass| klass.send(:include, DRbUndumped) }
+
+module Akephalos
+ class Server
+ def self.start!(socket_file)
+ client = Client.new
+ DRb.start_service("drbunix://#{socket_file}", client)
+ DRb.thread.join
+ end
+ end
+end
diff --git a/lib/akephalos/version.rb b/lib/akephalos/version.rb
new file mode 100644
index 0000000..f7f26e6
--- /dev/null
+++ b/lib/akephalos/version.rb
@@ -0,0 +1,3 @@
+module Akephalos #:nodoc
+ VERSION = "0.0.5"
+end
diff --git a/spec/driver/akephalos_driver_spec.rb b/spec/driver/akephalos_driver_spec.rb
new file mode 100644
index 0000000..d9dd670
--- /dev/null
+++ b/spec/driver/akephalos_driver_spec.rb
@@ -0,0 +1,12 @@
+require 'spec_helper'
+
+describe Capybara::Driver::Akephalos do
+
+ before do
+ @driver = Capybara::Driver::Akephalos.new(TestApp)
+ end
+
+ it_should_behave_like "driver"
+ it_should_behave_like "driver with javascript support"
+
+end
diff --git a/spec/filter_spec.rb b/spec/filter_spec.rb
new file mode 100644
index 0000000..8d93e3f
--- /dev/null
+++ b/spec/filter_spec.rb
@@ -0,0 +1,24 @@
+require 'spec_helper'
+
+describe "Filters" do
+ before do
+ @session = Capybara::Session.new(:akephalos, TestApp)
+ end
+
+ context "with no filter" do
+ it "returns the page's source" do
+ @session.visit "/"
+ @session.source.should == "Hello world!"
+ end
+ end
+
+ context "with a filter" do
+ after { Akephalos.filters.clear }
+
+ it "returns the filter's source" do
+ Akephalos.filter :get, %r{.*}, :body => "Howdy!"
+ @session.visit "/"
+ @session.source.should == "Howdy!"
+ end
+ end
+end
diff --git a/spec/session/akephalos_session_spec.rb b/spec/session/akephalos_session_spec.rb
new file mode 100644
index 0000000..3ace097
--- /dev/null
+++ b/spec/session/akephalos_session_spec.rb
@@ -0,0 +1,26 @@
+require 'spec_helper'
+
+describe Capybara::Session do
+ context 'with akephalos driver' do
+
+ before do
+ @session = Capybara::Session.new(:akephalos, TestApp)
+ end
+
+ describe '#driver' do
+ it "should be a headless driver" do
+ @session.driver.should be_an_instance_of(Capybara::Driver::Akephalos)
+ end
+ end
+
+ describe '#mode' do
+ it "should remember the mode" do
+ @session.mode.should == :akephalos
+ end
+ end
+
+ it_should_behave_like "session"
+ it_should_behave_like "session with javascript support"
+
+ end
+end
diff --git a/spec/slow_page_loads_spec.rb b/spec/slow_page_loads_spec.rb
new file mode 100644
index 0000000..047f67c
--- /dev/null
+++ b/spec/slow_page_loads_spec.rb
@@ -0,0 +1,66 @@
+require 'spec_helper'
+
+class SlowApp < TestApp
+ get '/slow_page' do
+ sleep 1
+ "<p>Loaded!</p>"
+ end
+
+ get '/really_slow_page' do
+ sleep 5
+ end
+
+ get '/slow_ajax_load' do
+ <<-HTML
+ <head>
+ <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
+ <title>with_js</title>
+ <script src="/jquery.js" type="text/javascript" charset="utf-8"></script>
+ <script type="text/javascript">
+ $(function() {
+ $('#ajax_load').click(function() {
+ // $('body').html("<p>Loaded!</p>");
+ $('body').load('/slow_page');
+ return false;
+ });
+ });
+ </script>
+ </head>
+ <body>
+ <a href="#" id="ajax_load">Click me</a>
+ </body>
+ HTML
+ end
+end
+
+if $0 == __FILE__
+ if __FILE__ == $0
+ Rack::Handler::Mongrel.run SlowApp, :Port => 8070
+ end
+end
+
+describe Capybara::Session do
+ context 'with akephalos driver' do
+
+ before do
+ @session = Capybara::Session.new(:akephalos, SlowApp)
+ end
+
+ context "slow page load" do
+ it "should wait for the page to finish loading" do
+ @session.visit('/slow_page')
+ @session.current_url.should include('/slow_page')
+ end
+ end
+
+ context "slow ajax load" do
+ it "should wait for ajax to load" do
+ @session.visit('/slow_ajax_load')
+ @session.click_link('Click me')
+ @session.should have_xpath("//p[contains(.,'Loaded!')]")
+ end
+ end
+
+ end
+end
+
diff --git a/spec/spec.opts b/spec/spec.opts
new file mode 100644
index 0000000..0d9a0dd
--- /dev/null
+++ b/spec/spec.opts
@@ -0,0 +1,2 @@
+--colour
+--format nested
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..9b9d53f
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,19 @@
+require 'rubygems'
+
+root = File.expand_path('../../', __FILE__)
+%w(vendor lib src).each do |dir|
+ dir = File.join(root, dir)
+ $:.unshift dir unless $:.include?(dir)
+end
+
+require 'akephalos'
+
+spec_dir = nil
+$:.detect do |dir|
+ if File.exists? File.join(dir, "capybara.rb")
+ spec_dir = File.expand_path(File.join(dir,"..","spec"))
+ $:.unshift( spec_dir )
+ end
+end
+
+require File.join(spec_dir,"spec_helper")
diff --git a/src/htmlunit/commons-codec-1.4.jar b/src/htmlunit/commons-codec-1.4.jar
new file mode 100644
index 0000000..458d432
Binary files /dev/null and b/src/htmlunit/commons-codec-1.4.jar differ
diff --git a/src/htmlunit/commons-collections-3.2.1.jar b/src/htmlunit/commons-collections-3.2.1.jar
new file mode 100644
index 0000000..c35fa1f
Binary files /dev/null and b/src/htmlunit/commons-collections-3.2.1.jar differ
diff --git a/src/htmlunit/commons-httpclient-3.1.jar b/src/htmlunit/commons-httpclient-3.1.jar
new file mode 100644
index 0000000..7c59774
Binary files /dev/null and b/src/htmlunit/commons-httpclient-3.1.jar differ
diff --git a/src/htmlunit/commons-io-1.4.jar b/src/htmlunit/commons-io-1.4.jar
new file mode 100644
index 0000000..133dc6c
Binary files /dev/null and b/src/htmlunit/commons-io-1.4.jar differ
diff --git a/src/htmlunit/commons-lang-2.4.jar b/src/htmlunit/commons-lang-2.4.jar
new file mode 100644
index 0000000..532939e
Binary files /dev/null and b/src/htmlunit/commons-lang-2.4.jar differ
diff --git a/src/htmlunit/commons-logging-1.1.1.jar b/src/htmlunit/commons-logging-1.1.1.jar
new file mode 100644
index 0000000..1deef14
Binary files /dev/null and b/src/htmlunit/commons-logging-1.1.1.jar differ
diff --git a/src/htmlunit/cssparser-0.9.5.jar b/src/htmlunit/cssparser-0.9.5.jar
new file mode 100644
index 0000000..9fc2767
Binary files /dev/null and b/src/htmlunit/cssparser-0.9.5.jar differ
diff --git a/src/htmlunit/htmlunit-2.7.jar b/src/htmlunit/htmlunit-2.7.jar
new file mode 100644
index 0000000..6cd0122
Binary files /dev/null and b/src/htmlunit/htmlunit-2.7.jar differ
diff --git a/src/htmlunit/htmlunit-core-js-2.7.jar b/src/htmlunit/htmlunit-core-js-2.7.jar
new file mode 100644
index 0000000..7d9cc00
Binary files /dev/null and b/src/htmlunit/htmlunit-core-js-2.7.jar differ
diff --git a/src/htmlunit/nekohtml-1.9.14.jar b/src/htmlunit/nekohtml-1.9.14.jar
new file mode 100644
index 0000000..ba65542
Binary files /dev/null and b/src/htmlunit/nekohtml-1.9.14.jar differ
diff --git a/src/htmlunit/sac-1.3.jar b/src/htmlunit/sac-1.3.jar
new file mode 100644
index 0000000..39b92b1
Binary files /dev/null and b/src/htmlunit/sac-1.3.jar differ
diff --git a/src/htmlunit/serializer-2.7.1.jar b/src/htmlunit/serializer-2.7.1.jar
new file mode 100644
index 0000000..99f98db
Binary files /dev/null and b/src/htmlunit/serializer-2.7.1.jar differ
diff --git a/src/htmlunit/xalan-2.7.1.jar b/src/htmlunit/xalan-2.7.1.jar
new file mode 100644
index 0000000..458fa73
Binary files /dev/null and b/src/htmlunit/xalan-2.7.1.jar differ
diff --git a/src/htmlunit/xercesImpl-2.9.1.jar b/src/htmlunit/xercesImpl-2.9.1.jar
new file mode 100644
index 0000000..547f563
Binary files /dev/null and b/src/htmlunit/xercesImpl-2.9.1.jar differ
diff --git a/src/htmlunit/xml-apis-1.3.04.jar b/src/htmlunit/xml-apis-1.3.04.jar
new file mode 100644
index 0000000..d42c0ea
Binary files /dev/null and b/src/htmlunit/xml-apis-1.3.04.jar differ
diff --git a/tasks/docs.rake b/tasks/docs.rake
new file mode 100644
index 0000000..5a91f74
--- /dev/null
+++ b/tasks/docs.rake
@@ -0,0 +1,109 @@
+begin
+ require 'yard'
+ require 'haml'
+ desc 'Build all documentation'
+ task :docs => %w[docs:static docs:api]
+ task :doc => :docs # alias for docs
+
+ CLEAN.include 'docs/build'
+
+ desc 'Build API documentation (docs/api)'
+ task 'docs:api' => ['docs/build/.git'] do
+ sh("yardoc -o docs/build/api lib/**/*.rb")
+ end
+
+ desc 'Build static documentation (docs)'
+ task 'docs:static' => ['docs/build/.git'] do
+ require 'pathname'
+ require 'fileutils'
+ require 'rubygems'
+ require 'haml'
+
+ module Highlighting
+ def highlight(language, text)
+ code = ""
+ IO.popen("pygmentize -l#{language} -fhtml", "w+") do |io|
+ io.write(text)
+ io.close_write
+ code = io.read
+ end
+ code
+ end
+ end
+
+ module Haml::Filters::Code
+ include Highlighting
+ include Haml::Filters::Base
+ def render(text)
+ highlight('ruby', text)
+ end
+ end
+
+ module Haml::Filters::Bash
+ include Highlighting
+ include Haml::Filters::Base
+ def render(text)
+ highlight('bash', text)
+ end
+ end
+
+ class GeneratorContext
+ end
+
+ layout = Haml::Engine.new(File.read("docs/layout.html.haml"))
+
+ FileList["docs/{stylesheets,images}/*"].each do |resource|
+ path = Pathname(resource)
+ relative_path = path.relative_path_from(Pathname("docs"))
+ build_path = Pathname("docs/build") + relative_path
+ FileUtils.mkdir_p(build_path.parent.to_s)
+ FileUtils.copy(resource, build_path)
+ end
+
+ FileList["docs/**/*.haml"].exclude("docs/layout.html.haml").each do |entry|
+ path = Pathname(entry)
+ relative_path = path.relative_path_from(Pathname("docs"))
+ build_path = Pathname("docs/build") + relative_path.parent + path.basename.sub(/\.haml$/, '')
+
+ FileUtils.mkdir_p(build_path.dirname)
+
+ File.open(build_path, "w") do |file|
+ context = GeneratorContext.new
+ content = ""
+
+ Dir.chdir(path.dirname) do
+ content = Haml::Engine.new(File.read(path.basename)).render(context)
+ end
+
+ puts "Writing: #{build_path.relative_path_from(Pathname("build"))}"
+ file.write build_path.extname == ".html" ? layout.render(context, :content => content) : content
+ end
+ end
+ end
+
+ # GITHUB PAGES ===============================================================
+
+ directory 'docs/build/'
+
+ desc 'Update gh-pages branch'
+ task :pages => ['docs/build/.git', :docs] do
+ rev = `git rev-parse --short HEAD`.strip
+ Dir.chdir 'docs/build' do
+ sh "git add ."
+ sh "git commit -m 'rebuild pages from #{rev}'" do |ok,res|
+ if ok
+ verbose { puts "gh-pages updated" }
+ sh "git push -q o HEAD:gh-pages"
+ end
+ end
+ end
+ end
+
+ # Update the pages/ directory clone
+ file 'docs/build/.git' => ['docs/build/', '.git/refs/heads/gh-pages'] do |f|
+ sh "cd docs/build && git init -q && git remote add o ../../.git" if !File.exist?(f.name)
+ sh "cd docs/build && git fetch -q o && git reset -q --hard o/gh-pages && touch ."
+ end
+rescue LoadError
+ warn "** Yard and Haml are required for generating documentation. Try: gem install yard haml **"
+end
diff --git a/tasks/spec.rake b/tasks/spec.rake
new file mode 100644
index 0000000..cdb3381
--- /dev/null
+++ b/tasks/spec.rake
@@ -0,0 +1,11 @@
+require 'spec/rake/spectask'
+Spec::Rake::SpecTask.new(:spec) do |spec|
+ spec.libs << 'lib' << 'spec'
+ spec.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+Spec::Rake::SpecTask.new(:rcov) do |spec|
+ spec.libs << 'lib' << 'spec'
+ spec.pattern = 'spec/**/*_spec.rb'
+ spec.rcov = true
+end
|
koterpillar/android-sasl
|
09dbf766dcd4c29f1ade0a28121a336e2b9e9eb7
|
Refined README
|
diff --git a/README b/README
index 43c757d..e5cee3f 100644
--- a/README
+++ b/README
@@ -1,6 +1,11 @@
This is a SASL stack for Android platform, adapted from GNU Classpath source.
+Intended for Smack, might prove useful for something else.
As neither java nor javax namespace can be modified, javax.security.sasl has
been moved to gnusasl.javax.security.sasl.
-Distributed under the terms of the GNU GPL (v2 or later at your choice).
\ No newline at end of file
+Please note that you have to add
+ java.security.Security.addProvider(new gnu.javax.crypto.jce.GnuSasl());
+before SASL authentication methods will be active.
+
+Distributed under the terms of the GNU GPL (v2 or later at your choice).
|
koterpillar/android-sasl
|
fd61e60283ebd4183911c9f8f03f248d2732767d
|
Added copyright notices
|
diff --git a/README b/README
index 7568a31..43c757d 100644
--- a/README
+++ b/README
@@ -1,6 +1,6 @@
This is a SASL stack for Android platform, adapted from GNU Classpath source.
As neither java nor javax namespace can be modified, javax.security.sasl has
been moved to gnusasl.javax.security.sasl.
-Distributed under the terms of the GNU GPL (v2 or later at your choice).
\ No newline at end of file
+Distributed under the terms of the GNU GPL (v2 or later at your choice).
\ No newline at end of file
diff --git a/classpath-0.98/gnu/java/security/hash/Whirlpool.java b/classpath-0.98/gnu/java/security/hash/Whirlpool.java
index d27ddbd..fc82ea8 100644
--- a/classpath-0.98/gnu/java/security/hash/Whirlpool.java
+++ b/classpath-0.98/gnu/java/security/hash/Whirlpool.java
@@ -1,518 +1,523 @@
/* Whirlpool.java --
Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.security.hash;
+import gnu.java.lang.CPStringBuilder;
+
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
/**
* Whirlpool, a new 512-bit hashing function operating on messages less than
* 2 ** 256 bits in length. The function structure is designed according to the
* Wide Trail strategy and permits a wide variety of implementation trade-offs.
* <p>
* This implementation is of Whirlpool Version 3, described in [1] last revised
* on May 24th, 2003.
* <p>
* <b>IMPORTANT</b>: This implementation is not thread-safe.
* <p>
* References:
* <ol>
* <li><a href="http://planeta.terra.com.br/informatica/paulobarreto/WhirlpoolPage.html">
* The WHIRLPOOL Hashing Function</a>.<br>
* <a href="mailto:[email protected]">Paulo S.L.M. Barreto</a> and
* <a href="mailto:[email protected]">Vincent Rijmen</a>.</li>
* </ol>
*/
public final class Whirlpool
extends BaseHash
{
private static final int BLOCK_SIZE = 64; // inner block size in bytes
/** The digest of the 0-bit long message. */
private static final String DIGEST0 =
"19FA61D75522A4669B44E39C1D2E1726C530232130D407F89AFEE0964997F7A7"
+ "3E83BE698B288FEBCF88E3E03C4F0757EA8964E59B63D93708B138CC42A66EB3";
/** Default number of rounds. */
private static final int R = 10;
/** Whirlpool S-box; p. 19. */
private static final String S_box = // p. 19 [WHIRLPOOL]
"\u1823\uc6E8\u87B8\u014F\u36A6\ud2F5\u796F\u9152"
+ "\u60Bc\u9B8E\uA30c\u7B35\u1dE0\ud7c2\u2E4B\uFE57"
+ "\u1577\u37E5\u9FF0\u4AdA\u58c9\u290A\uB1A0\u6B85"
+ "\uBd5d\u10F4\ucB3E\u0567\uE427\u418B\uA77d\u95d8"
+ "\uFBEE\u7c66\udd17\u479E\ucA2d\uBF07\uAd5A\u8333"
+ "\u6302\uAA71\uc819\u49d9\uF2E3\u5B88\u9A26\u32B0"
+ "\uE90F\ud580\uBEcd\u3448\uFF7A\u905F\u2068\u1AAE"
+ "\uB454\u9322\u64F1\u7312\u4008\uc3Ec\udBA1\u8d3d"
+ "\u9700\ucF2B\u7682\ud61B\uB5AF\u6A50\u45F3\u30EF"
+ "\u3F55\uA2EA\u65BA\u2Fc0\udE1c\uFd4d\u9275\u068A"
+ "\uB2E6\u0E1F\u62d4\uA896\uF9c5\u2559\u8472\u394c"
+ "\u5E78\u388c\ud1A5\uE261\uB321\u9c1E\u43c7\uFc04"
+ "\u5199\u6d0d\uFAdF\u7E24\u3BAB\ucE11\u8F4E\uB7EB"
+ "\u3c81\u94F7\uB913\u2cd3\uE76E\uc403\u5644\u7FA9"
+ "\u2ABB\uc153\udc0B\u9d6c\u3174\uF646\uAc89\u14E1"
+ "\u163A\u6909\u70B6\ud0Ed\ucc42\u98A4\u285c\uF886";
/** The 64-bit lookup tables; section 7.1 p. 13. */
private static final long[] T0 = new long[256];
private static final long[] T1 = new long[256];
private static final long[] T2 = new long[256];
private static final long[] T3 = new long[256];
private static final long[] T4 = new long[256];
private static final long[] T5 = new long[256];
private static final long[] T6 = new long[256];
private static final long[] T7 = new long[256];
/** The round constants. */
private static final long[] rc = new long[R];
/** caches the result of the correctness test, once executed. */
private static Boolean valid;
/** The 512-bit context as 8 longs. */
private long H0, H1, H2, H3, H4, H5, H6, H7;
/** Work area for computing the round key schedule. */
private long k00, k01, k02, k03, k04, k05, k06, k07;
private long Kr0, Kr1, Kr2, Kr3, Kr4, Kr5, Kr6, Kr7;
/** work area for transforming the 512-bit buffer. */
private long n0, n1, n2, n3, n4, n5, n6, n7;
private long nn0, nn1, nn2, nn3, nn4, nn5, nn6, nn7;
/** work area for holding block cipher's intermediate values. */
private long w0, w1, w2, w3, w4, w5, w6, w7;
static
{
+ long time = System.currentTimeMillis();
int ROOT = 0x11D; // para. 2.1 [WHIRLPOOL]
int i, r, j;
long s1, s2, s4, s5, s8, s9, t;
char c;
final byte[] S = new byte[256];
for (i = 0; i < 256; i++)
{
c = S_box.charAt(i >>> 1);
s1 = ((i & 1) == 0 ? c >>> 8 : c) & 0xFFL;
s2 = s1 << 1;
if (s2 > 0xFFL)
s2 ^= ROOT;
s4 = s2 << 1;
if (s4 > 0xFFL)
s4 ^= ROOT;
s5 = s4 ^ s1;
s8 = s4 << 1;
if (s8 > 0xFFL)
s8 ^= ROOT;
s9 = s8 ^ s1;
T0[i] = t = s1 << 56 | s1 << 48 | s4 << 40 | s1 << 32
| s8 << 24 | s5 << 16 | s2 << 8 | s9;
T1[i] = t >>> 8 | t << 56;
T2[i] = t >>> 16 | t << 48;
T3[i] = t >>> 24 | t << 40;
T4[i] = t >>> 32 | t << 32;
T5[i] = t >>> 40 | t << 24;
T6[i] = t >>> 48 | t << 16;
T7[i] = t >>> 56 | t << 8;
}
for (r = 0, i = 0; r < R; )
rc[r++] = (T0[i++] & 0xFF00000000000000L)
^ (T1[i++] & 0x00FF000000000000L)
^ (T2[i++] & 0x0000FF0000000000L)
^ (T3[i++] & 0x000000FF00000000L)
^ (T4[i++] & 0x00000000FF000000L)
^ (T5[i++] & 0x0000000000FF0000L)
^ (T6[i++] & 0x000000000000FF00L)
^ (T7[i++] & 0x00000000000000FFL);
+ time = System.currentTimeMillis() - time;
}
/** Trivial 0-arguments constructor. */
public Whirlpool()
{
super(Registry.WHIRLPOOL_HASH, 20, BLOCK_SIZE);
}
/**
* Private constructor for cloning purposes.
*
* @param md the instance to clone.
*/
private Whirlpool(Whirlpool md)
{
this();
this.H0 = md.H0;
this.H1 = md.H1;
this.H2 = md.H2;
this.H3 = md.H3;
this.H4 = md.H4;
this.H5 = md.H5;
this.H6 = md.H6;
this.H7 = md.H7;
this.count = md.count;
this.buffer = (byte[]) md.buffer.clone();
}
public Object clone()
{
return (new Whirlpool(this));
}
protected void transform(byte[] in, int offset)
{
// apply mu to the input
n0 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n1 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n2 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n3 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n4 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n5 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n6 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
n7 = (in[offset++] & 0xFFL) << 56
| (in[offset++] & 0xFFL) << 48
| (in[offset++] & 0xFFL) << 40
| (in[offset++] & 0xFFL) << 32
| (in[offset++] & 0xFFL) << 24
| (in[offset++] & 0xFFL) << 16
| (in[offset++] & 0xFFL) << 8
| (in[offset++] & 0xFFL);
// transform K into the key schedule Kr; 0 <= r <= R
k00 = H0;
k01 = H1;
k02 = H2;
k03 = H3;
k04 = H4;
k05 = H5;
k06 = H6;
k07 = H7;
nn0 = n0 ^ k00;
nn1 = n1 ^ k01;
nn2 = n2 ^ k02;
nn3 = n3 ^ k03;
nn4 = n4 ^ k04;
nn5 = n5 ^ k05;
nn6 = n6 ^ k06;
nn7 = n7 ^ k07;
// intermediate cipher output
w0 = w1 = w2 = w3 = w4 = w5 = w6 = w7 = 0L;
for (int r = 0; r < R; r++)
{
// 1. compute intermediate round key schedule by applying ro[rc]
// to the previous round key schedule --rc being the round constant
Kr0 = T0[(int)((k00 >> 56) & 0xFFL)]
^ T1[(int)((k07 >> 48) & 0xFFL)]
^ T2[(int)((k06 >> 40) & 0xFFL)]
^ T3[(int)((k05 >> 32) & 0xFFL)]
^ T4[(int)((k04 >> 24) & 0xFFL)]
^ T5[(int)((k03 >> 16) & 0xFFL)]
^ T6[(int)((k02 >> 8) & 0xFFL)]
^ T7[(int)( k01 & 0xFFL)] ^ rc[r];
Kr1 = T0[(int)((k01 >> 56) & 0xFFL)]
^ T1[(int)((k00 >> 48) & 0xFFL)]
^ T2[(int)((k07 >> 40) & 0xFFL)]
^ T3[(int)((k06 >> 32) & 0xFFL)]
^ T4[(int)((k05 >> 24) & 0xFFL)]
^ T5[(int)((k04 >> 16) & 0xFFL)]
^ T6[(int)((k03 >> 8) & 0xFFL)]
^ T7[(int)( k02 & 0xFFL)];
Kr2 = T0[(int)((k02 >> 56) & 0xFFL)]
^ T1[(int)((k01 >> 48) & 0xFFL)]
^ T2[(int)((k00 >> 40) & 0xFFL)]
^ T3[(int)((k07 >> 32) & 0xFFL)]
^ T4[(int)((k06 >> 24) & 0xFFL)]
^ T5[(int)((k05 >> 16) & 0xFFL)]
^ T6[(int)((k04 >> 8) & 0xFFL)]
^ T7[(int)( k03 & 0xFFL)];
Kr3 = T0[(int)((k03 >> 56) & 0xFFL)]
^ T1[(int)((k02 >> 48) & 0xFFL)]
^ T2[(int)((k01 >> 40) & 0xFFL)]
^ T3[(int)((k00 >> 32) & 0xFFL)]
^ T4[(int)((k07 >> 24) & 0xFFL)]
^ T5[(int)((k06 >> 16) & 0xFFL)]
^ T6[(int)((k05 >> 8) & 0xFFL)]
^ T7[(int)( k04 & 0xFFL)];
Kr4 = T0[(int)((k04 >> 56) & 0xFFL)]
^ T1[(int)((k03 >> 48) & 0xFFL)]
^ T2[(int)((k02 >> 40) & 0xFFL)]
^ T3[(int)((k01 >> 32) & 0xFFL)]
^ T4[(int)((k00 >> 24) & 0xFFL)]
^ T5[(int)((k07 >> 16) & 0xFFL)]
^ T6[(int)((k06 >> 8) & 0xFFL)]
^ T7[(int)( k05 & 0xFFL)];
Kr5 = T0[(int)((k05 >> 56) & 0xFFL)]
^ T1[(int)((k04 >> 48) & 0xFFL)]
^ T2[(int)((k03 >> 40) & 0xFFL)]
^ T3[(int)((k02 >> 32) & 0xFFL)]
^ T4[(int)((k01 >> 24) & 0xFFL)]
^ T5[(int)((k00 >> 16) & 0xFFL)]
^ T6[(int)((k07 >> 8) & 0xFFL)]
^ T7[(int)( k06 & 0xFFL)];
Kr6 = T0[(int)((k06 >> 56) & 0xFFL)]
^ T1[(int)((k05 >> 48) & 0xFFL)]
^ T2[(int)((k04 >> 40) & 0xFFL)]
^ T3[(int)((k03 >> 32) & 0xFFL)]
^ T4[(int)((k02 >> 24) & 0xFFL)]
^ T5[(int)((k01 >> 16) & 0xFFL)]
^ T6[(int)((k00 >> 8) & 0xFFL)]
^ T7[(int)( k07 & 0xFFL)];
Kr7 = T0[(int)((k07 >> 56) & 0xFFL)]
^ T1[(int)((k06 >> 48) & 0xFFL)]
^ T2[(int)((k05 >> 40) & 0xFFL)]
^ T3[(int)((k04 >> 32) & 0xFFL)]
^ T4[(int)((k03 >> 24) & 0xFFL)]
^ T5[(int)((k02 >> 16) & 0xFFL)]
^ T6[(int)((k01 >> 8) & 0xFFL)]
^ T7[(int)( k00 & 0xFFL)];
k00 = Kr0;
k01 = Kr1;
k02 = Kr2;
k03 = Kr3;
k04 = Kr4;
k05 = Kr5;
k06 = Kr6;
k07 = Kr7;
// 2. incrementally compute the cipher output
w0 = T0[(int)((nn0 >> 56) & 0xFFL)]
^ T1[(int)((nn7 >> 48) & 0xFFL)]
^ T2[(int)((nn6 >> 40) & 0xFFL)]
^ T3[(int)((nn5 >> 32) & 0xFFL)]
^ T4[(int)((nn4 >> 24) & 0xFFL)]
^ T5[(int)((nn3 >> 16) & 0xFFL)]
^ T6[(int)((nn2 >> 8) & 0xFFL)]
^ T7[(int)( nn1 & 0xFFL)] ^ Kr0;
w1 = T0[(int)((nn1 >> 56) & 0xFFL)]
^ T1[(int)((nn0 >> 48) & 0xFFL)]
^ T2[(int)((nn7 >> 40) & 0xFFL)]
^ T3[(int)((nn6 >> 32) & 0xFFL)]
^ T4[(int)((nn5 >> 24) & 0xFFL)]
^ T5[(int)((nn4 >> 16) & 0xFFL)]
^ T6[(int)((nn3 >> 8) & 0xFFL)]
^ T7[(int)( nn2 & 0xFFL)] ^ Kr1;
w2 = T0[(int)((nn2 >> 56) & 0xFFL)]
^ T1[(int)((nn1 >> 48) & 0xFFL)]
^ T2[(int)((nn0 >> 40) & 0xFFL)]
^ T3[(int)((nn7 >> 32) & 0xFFL)]
^ T4[(int)((nn6 >> 24) & 0xFFL)]
^ T5[(int)((nn5 >> 16) & 0xFFL)]
^ T6[(int)((nn4 >> 8) & 0xFFL)]
^ T7[(int)( nn3 & 0xFFL)] ^ Kr2;
w3 = T0[(int)((nn3 >> 56) & 0xFFL)]
^ T1[(int)((nn2 >> 48) & 0xFFL)]
^ T2[(int)((nn1 >> 40) & 0xFFL)]
^ T3[(int)((nn0 >> 32) & 0xFFL)]
^ T4[(int)((nn7 >> 24) & 0xFFL)]
^ T5[(int)((nn6 >> 16) & 0xFFL)]
^ T6[(int)((nn5 >> 8) & 0xFFL)]
^ T7[(int)( nn4 & 0xFFL)] ^ Kr3;
w4 = T0[(int)((nn4 >> 56) & 0xFFL)]
^ T1[(int)((nn3 >> 48) & 0xFFL)]
^ T2[(int)((nn2 >> 40) & 0xFFL)]
^ T3[(int)((nn1 >> 32) & 0xFFL)]
^ T4[(int)((nn0 >> 24) & 0xFFL)]
^ T5[(int)((nn7 >> 16) & 0xFFL)]
^ T6[(int)((nn6 >> 8) & 0xFFL)]
^ T7[(int)( nn5 & 0xFFL)] ^ Kr4;
w5 = T0[(int)((nn5 >> 56) & 0xFFL)]
^ T1[(int)((nn4 >> 48) & 0xFFL)]
^ T2[(int)((nn3 >> 40) & 0xFFL)]
^ T3[(int)((nn2 >> 32) & 0xFFL)]
^ T4[(int)((nn1 >> 24) & 0xFFL)]
^ T5[(int)((nn0 >> 16) & 0xFFL)]
^ T6[(int)((nn7 >> 8) & 0xFFL)]
^ T7[(int)( nn6 & 0xFFL)] ^ Kr5;
w6 = T0[(int)((nn6 >> 56) & 0xFFL)]
^ T1[(int)((nn5 >> 48) & 0xFFL)]
^ T2[(int)((nn4 >> 40) & 0xFFL)]
^ T3[(int)((nn3 >> 32) & 0xFFL)]
^ T4[(int)((nn2 >> 24) & 0xFFL)]
^ T5[(int)((nn1 >> 16) & 0xFFL)]
^ T6[(int)((nn0 >> 8) & 0xFFL)]
^ T7[(int)( nn7 & 0xFFL)] ^ Kr6;
w7 = T0[(int)((nn7 >> 56) & 0xFFL)]
^ T1[(int)((nn6 >> 48) & 0xFFL)]
^ T2[(int)((nn5 >> 40) & 0xFFL)]
^ T3[(int)((nn4 >> 32) & 0xFFL)]
^ T4[(int)((nn3 >> 24) & 0xFFL)]
^ T5[(int)((nn2 >> 16) & 0xFFL)]
^ T6[(int)((nn1 >> 8) & 0xFFL)]
^ T7[(int)( nn0 & 0xFFL)] ^ Kr7;
nn0 = w0;
nn1 = w1;
nn2 = w2;
nn3 = w3;
nn4 = w4;
nn5 = w5;
nn6 = w6;
nn7 = w7;
}
// apply the Miyaguchi-Preneel hash scheme
H0 ^= w0 ^ n0;
H1 ^= w1 ^ n1;
H2 ^= w2 ^ n2;
H3 ^= w3 ^ n3;
H4 ^= w4 ^ n4;
H5 ^= w5 ^ n5;
H6 ^= w6 ^ n6;
H7 ^= w7 ^ n7;
}
protected byte[] padBuffer()
{
// [WHIRLPOOL] p. 6:
// "...padded with a 1-bit, then with as few 0-bits as necessary to
// obtain a bit string whose length is an odd multiple of 256, and
// finally with the 256-bit right-justified binary representation of L."
// in this implementation we use 'count' as the number of bytes hashed
// so far. hence the minimal number of bytes added to the message proper
// are 33 (1 for the 1-bit followed by the 0-bits and the encoding of
// the count framed in a 256-bit block). our formula is then:
// count + 33 + padding = 0 (mod BLOCK_SIZE)
int n = (int)((count + 33) % BLOCK_SIZE);
int padding = n == 0 ? 33 : BLOCK_SIZE - n + 33;
byte[] result = new byte[padding];
// padding is always binary 1 followed by binary 0s
result[0] = (byte) 0x80;
// save (right justified) the number of bits hashed
long bits = count * 8;
int i = padding - 8;
result[i++] = (byte)(bits >>> 56);
result[i++] = (byte)(bits >>> 48);
result[i++] = (byte)(bits >>> 40);
result[i++] = (byte)(bits >>> 32);
result[i++] = (byte)(bits >>> 24);
result[i++] = (byte)(bits >>> 16);
result[i++] = (byte)(bits >>> 8);
result[i ] = (byte) bits;
return result;
}
protected byte[] getResult()
{
// apply inverse mu to the context
return new byte[] {
(byte)(H0 >>> 56), (byte)(H0 >>> 48), (byte)(H0 >>> 40), (byte)(H0 >>> 32),
(byte)(H0 >>> 24), (byte)(H0 >>> 16), (byte)(H0 >>> 8), (byte) H0,
(byte)(H1 >>> 56), (byte)(H1 >>> 48), (byte)(H1 >>> 40), (byte)(H1 >>> 32),
(byte)(H1 >>> 24), (byte)(H1 >>> 16), (byte)(H1 >>> 8), (byte) H1,
(byte)(H2 >>> 56), (byte)(H2 >>> 48), (byte)(H2 >>> 40), (byte)(H2 >>> 32),
(byte)(H2 >>> 24), (byte)(H2 >>> 16), (byte)(H2 >>> 8), (byte) H2,
(byte)(H3 >>> 56), (byte)(H3 >>> 48), (byte)(H3 >>> 40), (byte)(H3 >>> 32),
(byte)(H3 >>> 24), (byte)(H3 >>> 16), (byte)(H3 >>> 8), (byte) H3,
(byte)(H4 >>> 56), (byte)(H4 >>> 48), (byte)(H4 >>> 40), (byte)(H4 >>> 32),
(byte)(H4 >>> 24), (byte)(H4 >>> 16), (byte)(H4 >>> 8), (byte) H4,
(byte)(H5 >>> 56), (byte)(H5 >>> 48), (byte)(H5 >>> 40), (byte)(H5 >>> 32),
(byte)(H5 >>> 24), (byte)(H5 >>> 16), (byte)(H5 >>> 8), (byte) H5,
(byte)(H6 >>> 56), (byte)(H6 >>> 48), (byte)(H6 >>> 40), (byte)(H6 >>> 32),
(byte)(H6 >>> 24), (byte)(H6 >>> 16), (byte)(H6 >>> 8), (byte) H6,
(byte)(H7 >>> 56), (byte)(H7 >>> 48), (byte)(H7 >>> 40), (byte)(H7 >>> 32),
(byte)(H7 >>> 24), (byte)(H7 >>> 16), (byte)(H7 >>> 8), (byte) H7 };
}
protected void resetContext()
{
H0 = H1 = H2 = H3 = H4 = H5 = H6 = H7 = 0L;
}
public boolean selfTest()
{
if (valid == null)
{
String d = Util.toString(new Whirlpool().digest());
valid = Boolean.valueOf(DIGEST0.equals(d));
}
return valid.booleanValue();
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/jce/GnuSasl.java b/classpath-0.98/gnu/javax/crypto/jce/GnuSasl.java
index 78f310d..923b40a 100644
--- a/classpath-0.98/gnu/javax/crypto/jce/GnuSasl.java
+++ b/classpath-0.98/gnu/javax/crypto/jce/GnuSasl.java
@@ -1,125 +1,124 @@
/* GnuSasl.java -- javax.security.sasl algorithms.
Copyright (C) 2004, 2006 Free Software Foundation, Inc.
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.jce;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.ClientFactory;
import gnu.javax.crypto.sasl.ServerFactory;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.Provider;
-import java.security.Security;
import java.util.Set;
public final class GnuSasl
extends Provider
{
public GnuSasl()
{
super(Registry.GNU_SASL, 2.1, "GNU SASL Provider");
AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
// SASL Client and Server mechanisms
put("SaslClientFactory.ANONYMOUS",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslClientFactory.PLAIN",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslClientFactory.CRAM-MD5",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslClientFactory.SRP",
gnu.javax.crypto.sasl.ClientFactory.class.getName());
put("SaslServerFactory.ANONYMOUS",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.PLAIN",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.CRAM-MD5",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-MD5",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-SHA-160",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-RIPEMD128",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-RIPEMD160",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-TIGER",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("SaslServerFactory.SRP-WHIRLPOOL",
gnu.javax.crypto.sasl.ServerFactory.class.getName());
put("Alg.Alias.SaslServerFactory.SRP-SHS", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA1", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA-1", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-SHA160", "SRP-SHA-160");
put("Alg.Alias.SaslServerFactory.SRP-RIPEMD-128", "SRP-RIPEMD128");
put("Alg.Alias.SaslServerFactory.SRP-RIPEMD-160", "SRP-RIPEMD160");
return null;
}
});
}
/**
* Returns a {@link Set} of names of SASL Client mechanisms available from
* this {@link Provider}.
*
* @return a {@link Set} of SASL Client mechanisms (Strings).
*/
public static final Set getSaslClientMechanismNames()
{
return ClientFactory.getNames();
}
/**
* Returns a {@link Set} of names of SASL Server mechanisms available from
* this {@link Provider}.
*
* @return a {@link Set} of SASL Server mechanisms (Strings).
*/
public static final Set getSaslServerMechanismNames()
{
return ServerFactory.getNames();
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/ClientFactory.java b/classpath-0.98/gnu/javax/crypto/sasl/ClientFactory.java
index f845075..67b0447 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/ClientFactory.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/ClientFactory.java
@@ -1,168 +1,169 @@
/* ClientFactory.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.anonymous.AnonymousClient;
import gnu.javax.crypto.sasl.crammd5.CramMD5Client;
import gnu.javax.crypto.sasl.plain.PlainClient;
//import gnu.javax.crypto.sasl.srp.SRPClient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.callback.CallbackHandler;
import gnusasl.javax.security.sasl.Sasl;
import gnusasl.javax.security.sasl.SaslClient;
import gnusasl.javax.security.sasl.SaslClientFactory;
import gnusasl.javax.security.sasl.SaslException;
/**
* The implementation of {@link SaslClientFactory}.
*/
public class ClientFactory
implements SaslClientFactory
{
// implicit 0-arguments constructor
public static final Set getNames()
{
return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null))));
}
private static final String[] getNamesInternal(Map props)
{
String[] all = new String[] {
Registry.SASL_SRP_MECHANISM,
Registry.SASL_CRAM_MD5_MECHANISM,
Registry.SASL_PLAIN_MECHANISM,
Registry.SASL_ANONYMOUS_MECHANISM };
if (props == null)
return all;
if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props))
return new String[0];
List result = new ArrayList(all.length);
for (int i = 0; i < all.length;)
result.add(all[i++]);
if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props))
result.remove(Registry.SASL_PLAIN_MECHANISM);
if (hasPolicy(Sasl.POLICY_NOACTIVE, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
result.remove(Registry.SASL_PLAIN_MECHANISM);
}
if (hasPolicy(Sasl.POLICY_NODICTIONARY, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
result.remove(Registry.SASL_PLAIN_MECHANISM);
}
if (hasPolicy(Sasl.POLICY_NOANONYMOUS, props))
{
result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
}
if (hasPolicy(Sasl.POLICY_FORWARD_SECRECY, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
result.remove(Registry.SASL_PLAIN_MECHANISM);
}
return (String[]) result.toArray(new String[0]);
}
public static final ClientMechanism getInstance(String mechanism)
{
if (mechanism == null)
return null;
mechanism = mechanism.trim().toUpperCase();
// if (mechanism.equals(Registry.SASL_SRP_MECHANISM))
// return new SRPClient();
if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
return new CramMD5Client();
if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
return new PlainClient();
if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM))
return new AnonymousClient();
return null;
}
public SaslClient createSaslClient(String[] mechanisms,
String authorisationID, String protocol,
String serverName, Map props,
CallbackHandler cbh) throws SaslException
{
ClientMechanism result = null;
String mechanism;
for (int i = 0; i < mechanisms.length; i++)
{
mechanism = mechanisms[i];
result = getInstance(mechanism);
if (result != null)
break;
}
if (result != null)
{
HashMap attributes = new HashMap();
if (props != null)
attributes.putAll(props);
attributes.put(Registry.SASL_AUTHORISATION_ID, authorisationID);
attributes.put(Registry.SASL_PROTOCOL, protocol);
attributes.put(Registry.SASL_SERVER_NAME, serverName);
attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh);
result.init(attributes);
return result;
}
throw new SaslException("No supported mechanism found in given mechanism list");
}
public String[] getMechanismNames(Map props)
{
return getNamesInternal(props);
}
private static boolean hasPolicy(String propertyName, Map props)
{
return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName)));
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/ClientMechanism.java b/classpath-0.98/gnu/javax/crypto/sasl/ClientMechanism.java
index 8188dbf..9560192 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/ClientMechanism.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/ClientMechanism.java
@@ -1,293 +1,294 @@
/* ClientMechanism.java --
Copyright (C) 2003, 2005, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnu.java.security.Registry;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import gnusasl.javax.security.sasl.Sasl;
import gnusasl.javax.security.sasl.SaslClient;
import gnusasl.javax.security.sasl.SaslException;
/**
* A base class to facilitate implementing SASL client-side mechanisms.
*/
public abstract class ClientMechanism
implements SaslClient
{
/** Name of this mechanism. */
protected String mechanism;
/** The authorisation identity. */
protected String authorizationID;
/** Name of protocol using this mechanism. */
protected String protocol;
/** Name of server to authenticate to. */
protected String serverName;
/** Properties of qualities desired for this mechanism. */
protected Map properties;
/** Callback handler to use with this mechanism instance. */
protected CallbackHandler handler;
/** Channel binding data to use with this mechanism instance. */
protected byte[] channelBinding;
/** Whether authentication phase is completed (true) or not (false). */
protected boolean complete = false;
/** The state of the authentication automaton. */
protected int state = -1;
protected ClientMechanism(final String mechanism)
{
super();
this.mechanism = mechanism;
this.state = -1;
}
protected abstract void initMechanism() throws SaslException;
protected abstract void resetMechanism() throws SaslException;
public abstract byte[] evaluateChallenge(byte[] challenge)
throws SaslException;
public abstract boolean hasInitialResponse();
public boolean isComplete()
{
return complete;
}
public byte[] unwrap(final byte[] incoming, final int offset, final int len)
throws SaslException
{
if (! isComplete())
throw new IllegalMechanismStateException();
return this.engineUnwrap(incoming, offset, len);
}
public byte[] wrap(final byte[] outgoing, final int offset, final int len)
throws SaslException
{
if (! isComplete())
throw new IllegalMechanismStateException();
return this.engineWrap(outgoing, offset, len);
}
public String getMechanismName()
{
return mechanism;
}
public Object getNegotiatedProperty(final String propName)
{
if (! isComplete())
throw new IllegalStateException();
if (Sasl.QOP.equals(propName))
return getNegotiatedQOP();
if (Sasl.STRENGTH.equals(propName))
return getNegotiatedStrength();
if (Sasl.SERVER_AUTH.equals(propName))
return getNegotiatedServerAuth();
if (Sasl.MAX_BUFFER.equals(propName))
return getNegotiatedMaxBuffer();
if (Sasl.RAW_SEND_SIZE.equals(propName))
return getNegotiatedRawSendSize();
if (Sasl.POLICY_NOPLAINTEXT.equals(propName))
return getNegotiatedPolicyNoPlainText();
if (Sasl.POLICY_NOACTIVE.equals(propName))
return getNegotiatedPolicyNoActive();
if (Sasl.POLICY_NODICTIONARY.equals(propName))
return getNegotiatedPolicyNoDictionary();
if (Sasl.POLICY_NOANONYMOUS.equals(propName))
return getNegotiatedPolicyNoAnonymous();
if (Sasl.POLICY_FORWARD_SECRECY.equals(propName))
return getNegotiatedPolicyForwardSecrecy();
if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName))
return getNegotiatedPolicyPassCredentials();
if (Sasl.REUSE.equals(propName))
return getReuse();
return null;
}
public void dispose() throws SaslException
{
}
public String getAuthorizationID()
{
return authorizationID;
}
protected String getNegotiatedQOP()
{
return Registry.QOP_AUTH;
}
protected String getNegotiatedStrength()
{
return Registry.STRENGTH_LOW;
}
protected String getNegotiatedServerAuth()
{
return Registry.SERVER_AUTH_FALSE;
}
protected String getNegotiatedMaxBuffer()
{
return null;
}
protected String getNegotiatedRawSendSize()
{
return String.valueOf(Registry.SASL_BUFFER_MAX_LIMIT);
}
protected String getNegotiatedPolicyNoPlainText()
{
return null;
}
protected String getNegotiatedPolicyNoActive()
{
return null;
}
protected String getNegotiatedPolicyNoDictionary()
{
return null;
}
protected String getNegotiatedPolicyNoAnonymous()
{
return null;
}
protected String getNegotiatedPolicyForwardSecrecy()
{
return null;
}
protected String getNegotiatedPolicyPassCredentials()
{
return null;
}
protected String getReuse()
{
return Registry.REUSE_FALSE;
}
protected byte[] engineUnwrap(final byte[] incoming, final int offset,
final int len) throws SaslException
{
final byte[] result = new byte[len];
System.arraycopy(incoming, offset, result, 0, len);
return result;
}
protected byte[] engineWrap(final byte[] outgoing, final int offset,
final int len) throws SaslException
{
final byte[] result = new byte[len];
System.arraycopy(outgoing, offset, result, 0, len);
return result;
}
/**
* Initialises the mechanism with designated attributes. Permissible names and
* values are mechanism specific.
*
* @param attributes a set of name-value pairs that describes the desired
* future behaviour of this instance.
* @throws IllegalMechanismStateException if the instance is already
* initialised.
* @throws SaslException if an exception occurs during the process.
*/
public void init(final Map attributes) throws SaslException
{
if (state != -1)
throw new IllegalMechanismStateException("init()");
if (properties == null)
properties = new HashMap();
else
properties.clear();
if (attributes != null)
{
authorizationID = (String) attributes.get(Registry.SASL_AUTHORISATION_ID);
protocol = (String) attributes.get(Registry.SASL_PROTOCOL);
serverName = (String) attributes.get(Registry.SASL_SERVER_NAME);
handler = (CallbackHandler) attributes.get(Registry.SASL_CALLBACK_HANDLER);
channelBinding = (byte[]) attributes.get(Registry.SASL_CHANNEL_BINDING);
properties.putAll(attributes);
}
else
handler = null;
if (authorizationID == null)
authorizationID = "";
if (protocol == null)
protocol = "";
if (serverName == null)
serverName = "";
if (channelBinding == null)
channelBinding = new byte[0];
initMechanism();
complete = false;
state = 0;
}
/**
* Resets the mechanism instance for re-initialisation and use with other
* characteristics.
*
* @throws SaslException if an exception occurs during the process.
*/
public void reset() throws SaslException
{
resetMechanism();
properties.clear();
authorizationID = protocol = serverName = null;
channelBinding = null;
complete = false;
state = -1;
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java b/classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java
index 8da4a6c..dd78de3 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/IAuthInfoProvider.java
@@ -1,116 +1,117 @@
/* IAuthInfoProvider.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import java.util.Map;
import gnusasl.javax.security.sasl.AuthenticationException;
/**
* The visible methods of any authentication information provider.
*/
public interface IAuthInfoProvider
{
/**
* Activates (initialises) this provider instance. SHOULD be the first method
* invoked on the provider.
*
* @param context a collection of name-value bindings describing the
* activation context.
* @throws AuthenticationException if an exception occurs during the
* operation.
*/
void activate(Map context) throws AuthenticationException;
/**
* Passivates (releases) this provider instance. SHOULD be the last method
* invoked on the provider. Once it is done, no other method may be invoked on
* the same instance before it is <i>activated</i> agains.
*
* @throws AuthenticationException if an exception occurs during the
* operation.
*/
void passivate() throws AuthenticationException;
/**
* Checks if a user with a designated name is known to this provider.
*
* @param userName the name of a user to check.
* @return <code>true</code> if the user with the designated name is known
* to this provider; <code>false</code> otherwise.
* @throws AuthenticationException if an exception occurs during the
* operation.
*/
boolean contains(String userName) throws AuthenticationException;
/**
* Returns a collection of information about a designated user. The contents
* of the returned map is provider-specific of name-to-value mappings.
*
* @param userID a map of name-to-value bindings that fully describe a user.
* @return a collection of information about the designated user.
* @throws AuthenticationException if an exception occurs during the
* operation.
*/
Map lookup(Map userID) throws AuthenticationException;
/**
* Updates the credentials of a designated user.
*
* @param userCredentials a map of name-to-value bindings that fully describe
* a user, including per new credentials.
* @throws AuthenticationException if an exception occurs during the
* operation.
*/
void update(Map userCredentials) throws AuthenticationException;
/**
* A provider may operate in more than mode; e.g. SRP-II caters for user
* credentials computed in more than one message digest algorithm. This method
* returns the set of name-to-value bindings describing the mode of the
* provider.
*
* @param mode a unique identifier describing the operational mode.
* @return a collection of name-to-value bindings describing the designated
* mode.
* @throws AuthenticationException if an exception occurs during the
* operation.
*/
Map getConfiguration(String mode) throws AuthenticationException;
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/IllegalMechanismStateException.java b/classpath-0.98/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
index cc0399f..ef0a311 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/IllegalMechanismStateException.java
@@ -1,84 +1,85 @@
/* IllegalMechanismStateException.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnusasl.javax.security.sasl.AuthenticationException;
/**
* A checked exception thrown to indicate that an operation that should be
* invoked on a completed mechanism was invoked but the authentication phase of
* that mechanism was not completed yet, or that an operation that should be
* invoked on incomplete mechanisms was invoked but the authentication phase of
* that mechanism was already completed.
*/
public class IllegalMechanismStateException
extends AuthenticationException
{
/**
* Constructs a new instance of <code>IllegalMechanismStateException</code>
* with no detail message.
*/
public IllegalMechanismStateException()
{
super();
}
/**
* Constructs a new instance of <code>IllegalMechanismStateException</code>
* with the specified detail message.
*
* @param detail the detail message.
*/
public IllegalMechanismStateException(String detail)
{
super(detail);
}
/**
* Constructs a new instance of <code>IllegalMechanismStateException</code>
* with the specified detail message, and cause.
*
* @param detail the detail message.
* @param ex the original cause.
*/
public IllegalMechanismStateException(String detail, Throwable ex)
{
super(detail, ex);
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java b/classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java
index d3b3c94..74e1595 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/NoSuchUserException.java
@@ -1,67 +1,68 @@
/* NoSuchUserException.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnusasl.javax.security.sasl.AuthenticationException;
/**
* A checked exception thrown to indicate that a designated user is unknown to
* the authentication layer.
*/
public class NoSuchUserException
extends AuthenticationException
{
/** Constructs a <code>NoSuchUserException</code> with no detail message. */
public NoSuchUserException()
{
super();
}
/**
* Constructs a <code>NoSuchUserException</code> with the specified detail
* message. In the case of this exception, the detail message designates the
* offending username.
*
* @param arg the detail message, which in this case is the username.
*/
public NoSuchUserException(String arg)
{
super(arg);
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/ServerFactory.java b/classpath-0.98/gnu/javax/crypto/sasl/ServerFactory.java
index ce6798e..f420eec 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/ServerFactory.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/ServerFactory.java
@@ -1,158 +1,159 @@
/* ServerFactory.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.anonymous.AnonymousServer;
//import gnu.javax.crypto.sasl.crammd5.CramMD5Server;
//import gnu.javax.crypto.sasl.plain.PlainServer;
//import gnu.javax.crypto.sasl.srp.SRPServer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.security.auth.callback.CallbackHandler;
import gnusasl.javax.security.sasl.Sasl;
import gnusasl.javax.security.sasl.SaslException;
import gnusasl.javax.security.sasl.SaslServer;
import gnusasl.javax.security.sasl.SaslServerFactory;
/**
* The implementation of the {@link SaslServerFactory}.
*/
public class ServerFactory
implements SaslServerFactory
{
// implicit 0-arguments constructor
public static final Set getNames()
{
return Collections.unmodifiableSet(new HashSet(Arrays.asList(getNamesInternal(null))));
}
private static final String[] getNamesInternal(Map props)
{
String[] all = new String[] {
Registry.SASL_SRP_MECHANISM,
Registry.SASL_CRAM_MD5_MECHANISM,
Registry.SASL_PLAIN_MECHANISM,
Registry.SASL_ANONYMOUS_MECHANISM };
List result = new ArrayList(4);
int i;
for (i = 0; i < all.length;)
result.add(all[i++]);
if (props == null)
return (String[]) result.toArray(new String[0]); // all
if (hasPolicy(Sasl.POLICY_PASS_CREDENTIALS, props)) // none
return new String[0];
if (hasPolicy(Sasl.POLICY_NOPLAINTEXT, props))
result.remove(Registry.SASL_PLAIN_MECHANISM);
if (hasPolicy(Sasl.POLICY_NOACTIVE, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
result.remove(Registry.SASL_PLAIN_MECHANISM);
}
if (hasPolicy(Sasl.POLICY_NODICTIONARY, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
result.remove(Registry.SASL_PLAIN_MECHANISM);
}
if (hasPolicy(Sasl.POLICY_NOANONYMOUS, props))
{
result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
}
if (hasPolicy(Sasl.POLICY_FORWARD_SECRECY, props))
{
result.remove(Registry.SASL_CRAM_MD5_MECHANISM);
result.remove(Registry.SASL_ANONYMOUS_MECHANISM);
result.remove(Registry.SASL_PLAIN_MECHANISM);
}
return (String[]) result.toArray(new String[0]);
}
public static final ServerMechanism getInstance(String mechanism)
{
if (mechanism == null)
return null;
mechanism = mechanism.trim().toUpperCase();
// if (mechanism.equals(Registry.SASL_SRP_MECHANISM))
// return new SRPServer();
// if (mechanism.equals(Registry.SASL_CRAM_MD5_MECHANISM))
// return new CramMD5Server();
// if (mechanism.equals(Registry.SASL_PLAIN_MECHANISM))
// return new PlainServer();
if (mechanism.equals(Registry.SASL_ANONYMOUS_MECHANISM))
return new AnonymousServer();
return null;
}
public SaslServer createSaslServer(String mechanism, String protocol,
String serverName, Map props,
CallbackHandler cbh) throws SaslException
{
ServerMechanism result = getInstance(mechanism);
if (result != null)
{
HashMap attributes = new HashMap();
if (props != null)
attributes.putAll(props);
attributes.put(Registry.SASL_PROTOCOL, protocol);
attributes.put(Registry.SASL_SERVER_NAME, serverName);
attributes.put(Registry.SASL_CALLBACK_HANDLER, cbh);
result.init(attributes);
}
return result;
}
public String[] getMechanismNames(Map props)
{
return getNamesInternal(props);
}
private static boolean hasPolicy(String propertyName, Map props)
{
return "true".equalsIgnoreCase(String.valueOf(props.get(propertyName)));
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/ServerMechanism.java b/classpath-0.98/gnu/javax/crypto/sasl/ServerMechanism.java
index 51a40e9..98bba6c 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/ServerMechanism.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/ServerMechanism.java
@@ -1,294 +1,295 @@
/* ServerMechanism.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnu.java.security.Registry;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
import gnusasl.javax.security.sasl.Sasl;
import gnusasl.javax.security.sasl.SaslException;
import gnusasl.javax.security.sasl.SaslServer;
/**
* A base class to facilitate implementing SASL server-side mechanisms.
*/
public abstract class ServerMechanism
implements SaslServer
{
/** Name of this mechanism. */
protected String mechanism;
/** Name of protocol using this mechanism. */
protected String protocol;
/** Name of server to authenticate to. */
protected String serverName;
/** Properties of qualities desired for this mechanism. */
protected Map properties;
/** Callback handler to use with this mechanism instance. */
protected CallbackHandler handler;
/** Whether authentication phase is completed (true) or not (false). */
protected boolean complete = false;
/** The authorisation identity. */
protected String authorizationID;
/** Channel binding data to use with this mechanism instance. */
protected byte[] channelBinding;
/** The state of the authentication automaton. -1 means uninitialised. */
protected int state = -1;
/** The provider for authentication information. */
protected IAuthInfoProvider authenticator;
protected ServerMechanism(final String mechanism)
{
super();
this.mechanism = mechanism;
this.authenticator = AuthInfo.getProvider(mechanism);
this.state = -1;
}
protected abstract void initMechanism() throws SaslException;
protected abstract void resetMechanism() throws SaslException;
public abstract byte[] evaluateResponse(byte[] response) throws SaslException;
public boolean isComplete()
{
return complete;
}
public byte[] unwrap(final byte[] incoming, final int offset, final int len)
throws SaslException
{
if (! isComplete())
throw new IllegalMechanismStateException();
return this.engineUnwrap(incoming, offset, len);
}
public byte[] wrap(final byte[] outgoing, final int offset, final int len)
throws SaslException
{
if (! isComplete())
throw new IllegalMechanismStateException();
return this.engineWrap(outgoing, offset, len);
}
public String getMechanismName()
{
return this.mechanism;
}
public String getAuthorizationID()
{
return this.authorizationID;
}
public Object getNegotiatedProperty(final String propName)
{
if (! isComplete())
throw new IllegalStateException();
if (Sasl.QOP.equals(propName))
return getNegotiatedQOP();
if (Sasl.STRENGTH.equals(propName))
return getNegotiatedStrength();
if (Sasl.SERVER_AUTH.equals(propName))
return getNegotiatedServerAuth();
if (Sasl.MAX_BUFFER.equals(propName))
return getNegotiatedMaxBuffer();
if (Sasl.RAW_SEND_SIZE.equals(propName))
return getNegotiatedRawSendSize();
if (Sasl.POLICY_NOPLAINTEXT.equals(propName))
return getNegotiatedPolicyNoPlainText();
if (Sasl.POLICY_NOACTIVE.equals(propName))
return getNegotiatedPolicyNoActive();
if (Sasl.POLICY_NODICTIONARY.equals(propName))
return getNegotiatedPolicyNoDictionary();
if (Sasl.POLICY_NOANONYMOUS.equals(propName))
return getNegotiatedPolicyNoAnonymous();
if (Sasl.POLICY_FORWARD_SECRECY.equals(propName))
return getNegotiatedPolicyForwardSecrecy();
if (Sasl.POLICY_PASS_CREDENTIALS.equals(propName))
return getNegotiatedPolicyPassCredentials();
if (Sasl.REUSE.equals(propName))
return getReuse();
return null;
}
public void dispose() throws SaslException
{
reset();
}
protected String getNegotiatedQOP()
{
return Registry.QOP_AUTH;
}
protected String getNegotiatedStrength()
{
return Registry.STRENGTH_LOW;
}
protected String getNegotiatedServerAuth()
{
return Registry.SERVER_AUTH_FALSE;
}
protected String getNegotiatedMaxBuffer()
{
return null;
}
protected String getNegotiatedPolicyNoPlainText()
{
return null;
}
protected String getNegotiatedPolicyNoActive()
{
return null;
}
protected String getNegotiatedPolicyNoDictionary()
{
return null;
}
protected String getNegotiatedPolicyNoAnonymous()
{
return null;
}
protected String getNegotiatedPolicyForwardSecrecy()
{
return null;
}
protected String getNegotiatedPolicyPassCredentials()
{
return null;
}
protected String getNegotiatedRawSendSize()
{
return String.valueOf(Registry.SASL_BUFFER_MAX_LIMIT);
}
protected String getReuse()
{
return Registry.REUSE_FALSE;
}
protected byte[] engineUnwrap(final byte[] incoming, final int offset,
final int len) throws SaslException
{
final byte[] result = new byte[len];
System.arraycopy(incoming, offset, result, 0, len);
return result;
}
protected byte[] engineWrap(final byte[] outgoing, final int offset,
final int len) throws SaslException
{
final byte[] result = new byte[len];
System.arraycopy(outgoing, offset, result, 0, len);
return result;
}
/**
* Initialises the mechanism with designated attributes. Permissible names and
* values are mechanism specific.
*
* @param attributes a set of name-value pairs that describes the desired
* future behaviour of this instance.
* @throws IllegalMechanismStateException if the instance is already
* initialised.
* @throws SaslException if an exception occurs during the process.
*/
public void init(final Map attributes) throws SaslException
{
if (state != -1)
throw new IllegalMechanismStateException("init()");
if (properties == null)
properties = new HashMap();
else
properties.clear();
if (attributes != null)
{
protocol = (String) attributes.get(Registry.SASL_PROTOCOL);
serverName = (String) attributes.get(Registry.SASL_SERVER_NAME);
handler = (CallbackHandler) attributes.get(Registry.SASL_CALLBACK_HANDLER);
channelBinding = (byte[]) attributes.get(Registry.SASL_CHANNEL_BINDING);
properties.putAll(attributes);
}
else
handler = null;
if (protocol == null)
protocol = "";
if (serverName == null)
serverName = "";
if (authenticator != null)
authenticator.activate(properties);
if (channelBinding == null)
channelBinding = new byte[0];
initMechanism();
complete = false;
state = 0;
}
/**
* Resets the mechanism instance for re-initialisation and use with other
* characteristics.
*
* @throws SaslException if an exception occurs during the process.
*/
public void reset() throws SaslException
{
resetMechanism();
properties.clear();
if (authenticator != null)
authenticator.passivate();
protocol = serverName = null;
channelBinding = null;
complete = false;
state = -1;
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/UserAlreadyExistsException.java b/classpath-0.98/gnu/javax/crypto/sasl/UserAlreadyExistsException.java
index 688e412..0f949a8 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/UserAlreadyExistsException.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/UserAlreadyExistsException.java
@@ -1,70 +1,71 @@
/* UserAlreadyExistsException.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl;
import gnusasl.javax.security.sasl.SaslException;
/**
* A checked exception thrown to indicate that a designated user is already
* known to the the authentication layer.
*/
public class UserAlreadyExistsException
extends SaslException
{
/**
* Constructs a <code>UserAlreadyExistsException</code> with no detail
* message.
*/
public UserAlreadyExistsException()
{
super();
}
/**
* Constructs a <code>UserAlreadyExistsException</code> with the specified
* detail message. In the case of this exception, the detail message
* designates the offending username.
*
* @param userName the detail message, which in this case is the username.
*/
public UserAlreadyExistsException(String userName)
{
super(userName);
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java b/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
index c3630c5..d2ea24a 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousClient.java
@@ -1,102 +1,103 @@
/* AnonymousClient.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.anonymous;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.ClientMechanism;
import gnu.javax.crypto.sasl.IllegalMechanismStateException;
import java.io.UnsupportedEncodingException;
import gnusasl.javax.security.sasl.AuthenticationException;
import gnusasl.javax.security.sasl.SaslClient;
import gnusasl.javax.security.sasl.SaslException;
/**
* The ANONYMOUS client-side mechanism.
*/
public class AnonymousClient
extends ClientMechanism
implements SaslClient
{
public AnonymousClient()
{
super(Registry.SASL_ANONYMOUS_MECHANISM);
}
protected void initMechanism() throws SaslException
{
}
protected void resetMechanism() throws SaslException
{
}
public boolean hasInitialResponse()
{
return true;
}
public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
{
if (complete)
{
throw new IllegalMechanismStateException("evaluateChallenge()");
}
return response();
}
private byte[] response() throws SaslException
{
if (! AnonymousUtil.isValidTraceInformation(authorizationID))
throw new AuthenticationException(
"Authorisation ID is not a valid email address");
complete = true;
final byte[] result;
try
{
result = authorizationID.getBytes("UTF-8");
}
catch (UnsupportedEncodingException x)
{
throw new AuthenticationException("response()", x);
}
return result;
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java b/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java
index 7ad7a5a..cfc3336 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/anonymous/AnonymousServer.java
@@ -1,90 +1,91 @@
/* AnonymousServer.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.anonymous;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.ServerMechanism;
import java.io.UnsupportedEncodingException;
import gnusasl.javax.security.sasl.AuthenticationException;
import gnusasl.javax.security.sasl.SaslException;
import gnusasl.javax.security.sasl.SaslServer;
/**
* The ANONYMOUS server-side mechanism.
*/
public class AnonymousServer
extends ServerMechanism
implements SaslServer
{
public AnonymousServer()
{
super(Registry.SASL_ANONYMOUS_MECHANISM);
}
protected void initMechanism() throws SaslException
{
}
protected void resetMechanism() throws SaslException
{
}
public byte[] evaluateResponse(final byte[] response) throws SaslException
{
if (response == null)
return null;
try
{
authorizationID = new String(response, "UTF-8");
}
catch (UnsupportedEncodingException x)
{
throw new AuthenticationException("evaluateResponse()", x);
}
if (AnonymousUtil.isValidTraceInformation(authorizationID))
{
this.complete = true;
return null;
}
authorizationID = null;
throw new AuthenticationException("Invalid email address");
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java b/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java
index 0c9b769..18835a7 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5AuthInfoProvider.java
@@ -1,166 +1,167 @@
/* CramMD5AuthInfoProvider.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.crammd5;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.IAuthInfoProvider;
import gnu.javax.crypto.sasl.NoSuchUserException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import gnusasl.javax.security.sasl.AuthenticationException;
/**
* The CRAM-MD5 mechanism authentication information provider implementation.
*/
public class CramMD5AuthInfoProvider
implements IAuthInfoProvider
{
private PasswordFile passwordFile = null;
// implicit 0-args constrcutor
public void activate(Map context) throws AuthenticationException
{
try
{
if (context == null)
passwordFile = new PasswordFile();
else
{
String pfn = (String) context.get(CramMD5Registry.PASSWORD_FILE);
if (pfn == null)
passwordFile = new PasswordFile();
else
passwordFile = new PasswordFile(pfn);
}
}
catch (IOException x)
{
throw new AuthenticationException("activate()", x);
}
}
public void passivate() throws AuthenticationException
{
passwordFile = null;
}
public boolean contains(String userName) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("contains()",
new IllegalStateException());
boolean result = false;
try
{
result = passwordFile.contains(userName);
}
catch (IOException x)
{
throw new AuthenticationException("contains()", x);
}
return result;
}
public Map lookup(Map userID) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("lookup()", new IllegalStateException());
Map result = new HashMap();
try
{
String userName = (String) userID.get(Registry.SASL_USERNAME);
if (userName == null)
throw new NoSuchUserException("");
String[] data = passwordFile.lookup(userName);
result.put(Registry.SASL_USERNAME, data[0]);
result.put(Registry.SASL_PASSWORD, data[1]);
result.put(CramMD5Registry.UID_FIELD, data[2]);
result.put(CramMD5Registry.GID_FIELD, data[3]);
result.put(CramMD5Registry.GECOS_FIELD, data[4]);
result.put(CramMD5Registry.DIR_FIELD, data[5]);
result.put(CramMD5Registry.SHELL_FIELD, data[6]);
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("lookup()", x);
}
return result;
}
public void update(Map userCredentials) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("update()", new IllegalStateException());
try
{
String userName = (String) userCredentials.get(Registry.SASL_USERNAME);
String password = (String) userCredentials.get(Registry.SASL_PASSWORD);
String uid = (String) userCredentials.get(CramMD5Registry.UID_FIELD);
String gid = (String) userCredentials.get(CramMD5Registry.GID_FIELD);
String gecos = (String) userCredentials.get(CramMD5Registry.GECOS_FIELD);
String dir = (String) userCredentials.get(CramMD5Registry.DIR_FIELD);
String shell = (String) userCredentials.get(CramMD5Registry.SHELL_FIELD);
if (uid == null || gid == null || gecos == null || dir == null
|| shell == null)
passwordFile.changePasswd(userName, password);
else
{
String[] attributes = new String[] { uid, gid, gecos, dir, shell };
passwordFile.add(userName, password, attributes);
}
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("update()", x);
}
}
public Map getConfiguration(String mode) throws AuthenticationException
{
throw new AuthenticationException("", new UnsupportedOperationException());
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java b/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java
index 298230c..e1a110b 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Client.java
@@ -1,168 +1,169 @@
/* CramMD5Client.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.crammd5;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
import gnu.javax.crypto.sasl.ClientMechanism;
import java.io.IOException;
import java.security.InvalidKeyException;
import javax.security.auth.callback.Callback;
import gnusasl.javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import gnusasl.javax.security.sasl.AuthenticationException;
import gnusasl.javax.security.sasl.SaslClient;
import gnusasl.javax.security.sasl.SaslException;
/**
* The CRAM-MD5 SASL client-side mechanism.
*/
public class CramMD5Client
extends ClientMechanism
implements SaslClient
{
public CramMD5Client()
{
super(Registry.SASL_CRAM_MD5_MECHANISM);
}
protected void initMechanism() throws SaslException
{
}
protected void resetMechanism() throws SaslException
{
}
public boolean hasInitialResponse()
{
return false;
}
public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
{
if (challenge == null)
throw new SaslException("null challenge");
try
{
final String username;
final char[] password;
Callback[] callbacks;
if ((! properties.containsKey(Registry.SASL_USERNAME))
&& (! properties.containsKey(Registry.SASL_PASSWORD)))
{
callbacks = new Callback[2];
final NameCallback nameCB;
final String defaultName = System.getProperty("user.name");
if (defaultName == null)
nameCB = new NameCallback("username: ");
else
nameCB = new NameCallback("username: ", defaultName);
final PasswordCallback pwdCB = new PasswordCallback("password: ",
false);
callbacks[0] = nameCB;
callbacks[1] = pwdCB;
this.handler.handle(callbacks);
username = nameCB.getName();
password = pwdCB.getPassword();
}
else
{
if (properties.containsKey(Registry.SASL_USERNAME))
username = (String) properties.get(Registry.SASL_USERNAME);
else
{
callbacks = new Callback[1];
final NameCallback nameCB;
final String defaultName = System.getProperty("user.name");
if (defaultName == null)
nameCB = new NameCallback("username: ");
else
nameCB = new NameCallback("username: ", defaultName);
callbacks[0] = nameCB;
this.handler.handle(callbacks);
username = nameCB.getName();
}
if (properties.containsKey(Registry.SASL_PASSWORD))
password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray();
else
{
callbacks = new Callback[1];
final PasswordCallback pwdCB = new PasswordCallback("password: ",
false);
callbacks[0] = pwdCB;
this.handler.handle(callbacks);
password = pwdCB.getPassword();
}
}
if (password == null)
throw new SaslException("null password supplied");
final byte[] digest;
try
{
digest = CramMD5Util.createHMac(password, challenge);
}
catch (InvalidKeyException x)
{
throw new AuthenticationException("evaluateChallenge()", x);
}
final String response = username + " "
+ Util.toString(digest).toLowerCase();
this.complete = true;
return response.getBytes("UTF-8");
}
catch (UnsupportedCallbackException x)
{
throw new AuthenticationException("evaluateChallenge()", x);
}
catch (IOException x)
{
throw new AuthenticationException("evaluateChallenge()", x);
}
}
protected String getNegotiatedQOP()
{
return Registry.QOP_AUTH;
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java b/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java
index 9c5bf58..69ca9c5 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/crammd5/CramMD5Util.java
@@ -1,122 +1,123 @@
/* CramMD5Util.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.crammd5;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
import gnu.javax.crypto.mac.HMacFactory;
import gnu.javax.crypto.mac.IMac;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.util.HashMap;
import gnusasl.javax.security.sasl.SaslException;
/**
* A package-private CRAM-MD5-specific utility class.
*/
class CramMD5Util
{
private CramMD5Util()
{
super();
}
static byte[] createMsgID() throws SaslException
{
final String encoded;
try
{
encoded = Util.toBase64(Thread.currentThread().getName().getBytes("UTF-8"));
}
catch (UnsupportedEncodingException x)
{
throw new SaslException("createMsgID()", x);
}
String hostname = "localhost";
try
{
hostname = InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException ignored)
{
}
final byte[] result;
try
{
result = new CPStringBuilder("<")
.append(encoded.substring(0,encoded.length()))
.append(".").append(String.valueOf(System.currentTimeMillis()))
.append("@").append(hostname).append(">")
.toString()
.getBytes("UTF-8");
}
catch (UnsupportedEncodingException x)
{
throw new SaslException("createMsgID()", x);
}
return result;
}
static byte[] createHMac(final char[] passwd, final byte[] data)
throws InvalidKeyException, SaslException
{
final IMac mac = HMacFactory.getInstance(Registry.HMAC_NAME_PREFIX
+ Registry.MD5_HASH);
final HashMap map = new HashMap();
final byte[] km;
try
{
km = new String(passwd).getBytes("UTF-8");
}
catch (UnsupportedEncodingException x)
{
throw new SaslException("createHMac()", x);
}
map.put(IMac.MAC_KEY_MATERIAL, km);
mac.init(map);
mac.update(data, 0, data.length);
return mac.digest();
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java b/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java
index a5e1fd2..2f3d98a 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainAuthInfoProvider.java
@@ -1,166 +1,167 @@
/* PlainAuthInfoProvider.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.plain;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.IAuthInfoProvider;
import gnu.javax.crypto.sasl.NoSuchUserException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import gnusasl.javax.security.sasl.AuthenticationException;
/**
* The PLAIN mechanism authentication information provider implementation.
*/
public class PlainAuthInfoProvider
implements IAuthInfoProvider, PlainRegistry
{
private PasswordFile passwordFile = null;
// implicit 0-args constrcutor
public void activate(Map context) throws AuthenticationException
{
try
{
if (context == null)
passwordFile = new PasswordFile();
else
{
String pfn = (String) context.get(PASSWORD_FILE);
if (pfn == null)
passwordFile = new PasswordFile();
else
passwordFile = new PasswordFile(pfn);
}
}
catch (IOException x)
{
throw new AuthenticationException("activate()", x);
}
}
public void passivate() throws AuthenticationException
{
passwordFile = null;
}
public boolean contains(String userName) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("contains()",
new IllegalStateException());
boolean result = false;
try
{
result = passwordFile.contains(userName);
}
catch (IOException x)
{
throw new AuthenticationException("contains()", x);
}
return result;
}
public Map lookup(Map userID) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("lookup()", new IllegalStateException());
Map result = new HashMap();
try
{
String userName = (String) userID.get(Registry.SASL_USERNAME);
if (userName == null)
throw new NoSuchUserException("");
String[] data = passwordFile.lookup(userName);
result.put(Registry.SASL_USERNAME, data[0]);
result.put(Registry.SASL_PASSWORD, data[1]);
result.put(UID_FIELD, data[2]);
result.put(GID_FIELD, data[3]);
result.put(GECOS_FIELD, data[4]);
result.put(DIR_FIELD, data[5]);
result.put(SHELL_FIELD, data[6]);
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("lookup()", x);
}
return result;
}
public void update(Map userCredentials) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("update()", new IllegalStateException());
try
{
String userName = (String) userCredentials.get(Registry.SASL_USERNAME);
String password = (String) userCredentials.get(Registry.SASL_PASSWORD);
String uid = (String) userCredentials.get(UID_FIELD);
String gid = (String) userCredentials.get(GID_FIELD);
String gecos = (String) userCredentials.get(GECOS_FIELD);
String dir = (String) userCredentials.get(DIR_FIELD);
String shell = (String) userCredentials.get(SHELL_FIELD);
if (uid == null || gid == null || gecos == null || dir == null
|| shell == null)
passwordFile.changePasswd(userName, password);
else
{
String[] attributes = new String[] { uid, gid, gecos, dir, shell };
passwordFile.add(userName, password, attributes);
}
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("update()", x);
}
}
public Map getConfiguration(String mode) throws AuthenticationException
{
throw new AuthenticationException("", new UnsupportedOperationException());
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainClient.java b/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainClient.java
index b93ec2f..23d0689 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainClient.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/plain/PlainClient.java
@@ -1,156 +1,157 @@
/* PlainClient.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.plain;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Registry;
import gnu.javax.crypto.sasl.ClientMechanism;
import gnusasl.javax.security.sasl.SaslClient;
import gnusasl.javax.security.sasl.SaslException;
import javax.security.auth.callback.Callback;
import gnusasl.javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
/**
* The PLAIN SASL client-side mechanism.
*/
public class PlainClient
extends ClientMechanism
implements SaslClient
{
public PlainClient()
{
super(Registry.SASL_PLAIN_MECHANISM);
}
protected void initMechanism() throws SaslException
{
}
protected void resetMechanism() throws SaslException
{
}
public boolean hasInitialResponse()
{
return true;
}
public byte[] evaluateChallenge(final byte[] challenge) throws SaslException
{
try
{
final String username;
final char[] password;
Callback[] callbacks;
if ((! properties.containsKey(Registry.SASL_USERNAME))
&& (! properties.containsKey(Registry.SASL_PASSWORD)))
{
callbacks = new Callback[2];
final NameCallback nameCB;
final String defaultName = System.getProperty("user.name");
if (defaultName == null || defaultName.length() == 0)
nameCB = new NameCallback("username: ");
else
nameCB = new NameCallback("username: ", defaultName);
final PasswordCallback pwdCB = new PasswordCallback("password: ",
false);
callbacks[0] = nameCB;
callbacks[1] = pwdCB;
this.handler.handle(callbacks);
username = nameCB.getName();
password = pwdCB.getPassword();
}
else
{
if (properties.containsKey(Registry.SASL_USERNAME))
username = (String) properties.get(Registry.SASL_USERNAME);
else
{
callbacks = new Callback[1];
final NameCallback nameCB;
final String defaultName = System.getProperty("user.name");
if (defaultName == null)
nameCB = new NameCallback("username: ");
else
nameCB = new NameCallback("username: ", defaultName);
callbacks[0] = nameCB;
this.handler.handle(callbacks);
username = nameCB.getName();
}
if (properties.containsKey(Registry.SASL_PASSWORD))
password = ((String) properties.get(Registry.SASL_PASSWORD)).toCharArray();
else
{
callbacks = new Callback[1];
final PasswordCallback pwdCB = new PasswordCallback("password: ",
false);
callbacks[0] = pwdCB;
this.handler.handle(callbacks);
password = pwdCB.getPassword();
}
}
if (password == null)
throw new SaslException("null password supplied");
final CPStringBuilder sb = new CPStringBuilder();
if (authorizationID != null)
sb.append(authorizationID);
sb.append('\0');
sb.append(username);
sb.append('\0');
sb.append(password);
this.complete = true;
final byte[] response = sb.toString().getBytes("UTF-8");
return response;
}
catch (Exception x)
{
if (x instanceof SaslException)
throw (SaslException) x;
throw new SaslException("evaluateChallenge()", x);
}
}
protected String getNegotiatedQOP()
{
return Registry.QOP_AUTH;
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java b/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java
index 546e6b7..c6701cb 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPAuthInfoProvider.java
@@ -1,177 +1,178 @@
/* SRPAuthInfoProvider.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.srp;
import gnu.java.security.Registry;
import gnu.java.security.util.Util;
import gnu.javax.crypto.sasl.IAuthInfoProvider;
import gnu.javax.crypto.sasl.NoSuchUserException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import gnusasl.javax.security.sasl.AuthenticationException;
/**
* The SRP mechanism authentication information provider implementation.
*/
public class SRPAuthInfoProvider
implements IAuthInfoProvider
{
private PasswordFile passwordFile = null;
// implicit 0-args constrcutor
public void activate(Map context) throws AuthenticationException
{
try
{
if (context == null)
passwordFile = new PasswordFile();
else
{
passwordFile = (PasswordFile) context.get(SRPRegistry.PASSWORD_DB);
if (passwordFile == null)
{
String pfn = (String) context.get(SRPRegistry.PASSWORD_FILE);
if (pfn == null)
passwordFile = new PasswordFile();
else
passwordFile = new PasswordFile(pfn);
}
}
}
catch (IOException x)
{
throw new AuthenticationException("activate()", x);
}
}
public void passivate() throws AuthenticationException
{
passwordFile = null;
}
public boolean contains(String userName) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("contains()",
new IllegalStateException());
boolean result = false;
try
{
result = passwordFile.contains(userName);
}
catch (IOException x)
{
throw new AuthenticationException("contains()", x);
}
return result;
}
public Map lookup(Map userID) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("lookup()", new IllegalStateException());
Map result = new HashMap();
try
{
String userName = (String) userID.get(Registry.SASL_USERNAME);
if (userName == null)
throw new NoSuchUserException("");
String mdName = (String) userID.get(SRPRegistry.MD_NAME_FIELD);
String[] data = passwordFile.lookup(userName, mdName);
result.put(SRPRegistry.USER_VERIFIER_FIELD, data[0]);
result.put(SRPRegistry.SALT_FIELD, data[1]);
result.put(SRPRegistry.CONFIG_NDX_FIELD, data[2]);
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("lookup()", x);
}
return result;
}
public void update(Map userCredentials) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("update()", new IllegalStateException());
try
{
String userName = (String) userCredentials.get(Registry.SASL_USERNAME);
String password = (String) userCredentials.get(Registry.SASL_PASSWORD);
String salt = (String) userCredentials.get(SRPRegistry.SALT_FIELD);
String config = (String) userCredentials.get(SRPRegistry.CONFIG_NDX_FIELD);
if (salt == null || config == null)
passwordFile.changePasswd(userName, password);
else
passwordFile.add(userName, password, Util.fromBase64(salt), config);
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("update()", x);
}
}
public Map getConfiguration(String mode) throws AuthenticationException
{
if (passwordFile == null)
throw new AuthenticationException("getConfiguration()",
new IllegalStateException());
Map result = new HashMap();
try
{
String[] data = passwordFile.lookupConfig(mode);
result.put(SRPRegistry.SHARED_MODULUS, data[0]);
result.put(SRPRegistry.FIELD_GENERATOR, data[1]);
}
catch (Exception x)
{
if (x instanceof AuthenticationException)
throw (AuthenticationException) x;
throw new AuthenticationException("getConfiguration()", x);
}
return result;
}
}
diff --git a/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPServer.java b/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPServer.java
index 48f9cf6..e9ae8f4 100644
--- a/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPServer.java
+++ b/classpath-0.98/gnu/javax/crypto/sasl/srp/SRPServer.java
@@ -1,514 +1,515 @@
/* SRPServer.java --
Copyright (C) 2003, 2006 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is a part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
USA
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.javax.crypto.sasl.srp;
import gnu.java.lang.CPStringBuilder;
import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.util.PRNG;
import gnu.java.security.util.Util;
import gnu.javax.crypto.assembly.Direction;
import gnu.javax.crypto.cipher.CipherFactory;
import gnu.javax.crypto.cipher.IBlockCipher;
import gnu.javax.crypto.key.IKeyAgreementParty;
import gnu.javax.crypto.key.IncomingMessage;
import gnu.javax.crypto.key.KeyAgreementException;
import gnu.javax.crypto.key.KeyAgreementFactory;
import gnu.javax.crypto.key.OutgoingMessage;
import gnu.javax.crypto.key.srp6.SRP6KeyAgreement;
import gnu.javax.crypto.sasl.IllegalMechanismStateException;
import gnu.javax.crypto.sasl.InputBuffer;
import gnu.javax.crypto.sasl.IntegrityException;
import gnu.javax.crypto.sasl.OutputBuffer;
import gnu.javax.crypto.sasl.ServerMechanism;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import gnusasl.javax.security.sasl.AuthenticationException;
import gnusasl.javax.security.sasl.SaslException;
import gnusasl.javax.security.sasl.SaslServer;
/**
* The SASL-SRP server-side mechanism.
*/
public class SRPServer
extends ServerMechanism
implements SaslServer
{
private static final Logger log = Logger.getLogger(SRPServer.class.getName());
private String U = null; // client's username
private BigInteger N, g, A, B;
private byte[] s; // salt
private byte[] cIV, sIV; // client+server IVs, when confidentiality is on
private byte[] cn, sn; // client's and server's nonce
private SRP srp; // SRP algorithm instance used by this server
private byte[] sid; // session ID when re-used
private int ttl = 360; // session time-to-live in seconds
private byte[] cCB; // peer's channel binding'
private String mandatory; // List of available options
private String L = null;
private String o;
private String chosenIntegrityAlgorithm;
private String chosenConfidentialityAlgorithm;
private int rawSendSize = Registry.SASL_BUFFER_MAX_LIMIT;
private byte[] K; // shared session key
private boolean replayDetection = true; // whether Replay Detection is on
private int inCounter = 0; // messages sequence numbers
private int outCounter = 0;
private IALG inMac, outMac; // if !null, use for integrity
private CALG inCipher, outCipher; // if !null, use for confidentiality
private IKeyAgreementParty serverHandler =
KeyAgreementFactory.getPartyBInstance(Registry.SRP_SASL_KA);
/** Our default source of randomness. */
private PRNG prng = null;
public SRPServer()
{
super(Registry.SASL_SRP_MECHANISM);
}
protected void initMechanism() throws SaslException
{
// TODO:
// we must have a means to map a given username to a preferred
// SRP hash algorithm; otherwise we end up using _always_ SHA.
// for the time being get it from the mechanism properties map
// and apply it for all users.
final String mda = (String) properties.get(SRPRegistry.SRP_HASH);
srp = SRP.instance(mda == null ? SRPRegistry.SRP_DEFAULT_DIGEST_NAME : mda);
}
protected void resetMechanism() throws SaslException
{
s = null;
A = B = null;
K = null;
inMac = outMac = null;
inCipher = outCipher = null;
sid = null;
}
public byte[] evaluateResponse(final byte[] response) throws SaslException
{
switch (state)
{
case 0:
if (response == null)
return null;
state++;
return sendProtocolElements(response);
case 1:
if (! complete)
{
state++;
return sendEvidence(response);
}
// else fall through
default:
throw new IllegalMechanismStateException("evaluateResponse()");
}
}
protected byte[] engineUnwrap(final byte[] incoming, final int offset,
final int len) throws SaslException
{
if (Configuration.DEBUG)
log.entering(this.getClass().getName(), "engineUnwrap");
if (inMac == null && inCipher == null)
throw new IllegalStateException("connection is not protected");
if (Configuration.DEBUG)
log.fine("Incoming buffer (before security): "
+ Util.dumpString(incoming, offset, len));
// at this point one, or both, of confidentiality and integrity protection
// services are active.
final byte[] result;
try
{
if (inMac != null)
{ // integrity bytes are at the end of the stream
final int macBytesCount = inMac.length();
final int payloadLength = len - macBytesCount;
final byte[] received_mac = new byte[macBytesCount];
System.arraycopy(incoming, offset + payloadLength, received_mac, 0,
macBytesCount);
if (Configuration.DEBUG)
log.fine("Got C (received MAC): " + Util.dumpString(received_mac));
inMac.update(incoming, offset, payloadLength);
if (replayDetection)
{
inCounter++;
if (Configuration.DEBUG)
log.fine("inCounter=" + String.valueOf(inCounter));
inMac.update(new byte[] {
(byte)(inCounter >>> 24),
(byte)(inCounter >>> 16),
(byte)(inCounter >>> 8),
(byte) inCounter });
}
final byte[] computed_mac = inMac.doFinal();
if (Configuration.DEBUG)
log.fine("Computed MAC: " + Util.dumpString(computed_mac));
if (! Arrays.equals(received_mac, computed_mac))
throw new IntegrityException("engineUnwrap()");
// deal with the payload, which can be either plain or encrypted
if (inCipher != null)
result = inCipher.doFinal(incoming, offset, payloadLength);
else
{
result = new byte[payloadLength];
System.arraycopy(incoming, offset, result, 0, result.length);
}
}
else // no integrity protection; just confidentiality
result = inCipher.doFinal(incoming, offset, len);
}
catch (IOException x)
{
if (x instanceof SaslException)
throw (SaslException) x;
throw new SaslException("engineUnwrap()", x);
}
if (Configuration.DEBUG)
{
log.fine("Incoming buffer (after security): " + Util.dumpString(result));
log.exiting(this.getClass().getName(), "engineUnwrap");
}
return result;
}
protected byte[] engineWrap(final byte[] outgoing, final int offset,
final int len) throws SaslException
{
if (Configuration.DEBUG)
log.entering(this.getClass().getName(), "engineWrap");
if (outMac == null && outCipher == null)
throw new IllegalStateException("connection is not protected");
if (Configuration.DEBUG)
{
log.fine("Outgoing buffer (before security) (hex): "
+ Util.dumpString(outgoing, offset, len));
log.fine("Outgoing buffer (before security) (str): \""
+ new String(outgoing, offset, len) + "\"");
}
// at this point one, or both, of confidentiality and integrity protection
// services are active.
byte[] result;
try
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (outCipher != null)
{
result = outCipher.doFinal(outgoing, offset, len);
if (Configuration.DEBUG)
log.fine("Encoding c (encrypted plaintext): "
+ Util.dumpString(result));
out.write(result);
if (outMac != null)
{
outMac.update(result);
if (replayDetection)
{
outCounter++;
if (Configuration.DEBUG)
log.fine("outCounter=" + outCounter);
outMac.update(new byte[] {
(byte)(outCounter >>> 24),
(byte)(outCounter >>> 16),
(byte)(outCounter >>> 8),
(byte) outCounter });
}
final byte[] C = outMac.doFinal();
out.write(C);
if (Configuration.DEBUG)
log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
}
// else ciphertext only; do nothing
}
else // no confidentiality; just integrity [+ replay detection]
{
if (Configuration.DEBUG)
log.fine("Encoding p (plaintext): "
+ Util.dumpString(outgoing, offset, len));
out.write(outgoing, offset, len);
outMac.update(outgoing, offset, len);
if (replayDetection)
{
outCounter++;
if (Configuration.DEBUG)
log.fine("outCounter=" + outCounter);
outMac.update(new byte[] {
(byte)(outCounter >>> 24),
(byte)(outCounter >>> 16),
(byte)(outCounter >>> 8),
(byte) outCounter });
}
final byte[] C = outMac.doFinal();
out.write(C);
if (Configuration.DEBUG)
log.fine("Encoding C (integrity checksum): " + Util.dumpString(C));
}
result = out.toByteArray();
}
catch (IOException x)
{
if (x instanceof SaslException)
throw (SaslException) x;
throw new SaslException("engineWrap()", x);
}
if (Configuration.DEBUG)
log.exiting(this.getClass().getName(), "engineWrap");
return result;
}
protected String getNegotiatedQOP()
{
if (inMac != null)
{
if (inCipher != null)
return Registry.QOP_AUTH_CONF;
return Registry.QOP_AUTH_INT;
}
return Registry.QOP_AUTH;
}
protected String getNegotiatedStrength()
{
if (inMac != null)
{
if (inCipher != null)
return Registry.STRENGTH_HIGH;
return Registry.STRENGTH_MEDIUM;
}
return Registry.STRENGTH_LOW;
}
protected String getNegotiatedRawSendSize()
{
return String.valueOf(rawSendSize);
}
protected String getReuse()
{
return Registry.REUSE_TRUE;
}
private byte[] sendProtocolElements(final byte[] input) throws SaslException
{
if (Configuration.DEBUG)
{
log.entering(this.getClass().getName(), "sendProtocolElements");
log.fine("C: " + Util.dumpString(input));
}
// Client send U, I, sid, cn
final InputBuffer frameIn = new InputBuffer(input);
try
{
U = frameIn.getText(); // Extract username
if (Configuration.DEBUG)
log.fine("Got U (username): \"" + U + "\"");
authorizationID = frameIn.getText(); // Extract authorisation ID
if (Configuration.DEBUG)
log.fine("Got I (userid): \"" + authorizationID + "\"");
sid = frameIn.getEOS();
if (Configuration.DEBUG)
log.fine("Got sid (session ID): " + new String(sid));
cn = frameIn.getOS();
if (Configuration.DEBUG)
log.fine("Got cn (client nonce): " + Util.dumpString(cn));
cCB = frameIn.getEOS();
if (Configuration.DEBUG)
log.fine("Got cCB (client channel binding): " + Util.dumpString(cCB));
}
catch (IOException x)
{
if (x instanceof SaslException)
throw (SaslException) x;
throw new AuthenticationException("sendProtocolElements()", x);
}
// do/can we re-use?
if (ServerStore.instance().isAlive(sid))
{
final SecurityContext ctx = ServerStore.instance().restoreSession(sid);
srp = SRP.instance(ctx.getMdName());
K = ctx.getK();
cIV = ctx.getClientIV();
sIV = ctx.getServerIV();
replayDetection = ctx.hasReplayDetection();
inCounter = ctx.getInCounter();
outCounter = ctx.getOutCounter();
inMac = ctx.getInMac();
outMac = ctx.getOutMac();
inCipher = ctx.getInCipher();
outCipher = ctx.getOutCipher();
if (sn == null || sn.length != 16)
sn = new byte[16];
getDefaultPRNG().nextBytes(sn);
setupSecurityServices(false);
final OutputBuffer frameOut = new OutputBuffer();
try
{
frameOut.setScalar(1, 0xFF);
frameOut.setOS(sn);
frameOut.setEOS(channelBinding);
}
catch (IOException x)
{
if (x instanceof SaslException)
throw (SaslException) x;
throw new AuthenticationException("sendProtocolElements()", x);
}
final byte[] result = frameOut.encode();
if (Configuration.DEBUG)
{
log.fine("Old session...");
log.fine("S: " + Util.dumpString(result));
log.fine(" sn = " + Util.dumpString(sn));
log.fine(" sCB = " + Util.dumpString(channelBinding));
log.exiting(this.getClass().getName(), "sendProtocolElements");
}
return result;
}
else
{ // new session
authenticator.activate(properties);
// -------------------------------------------------------------------
final HashMap mapB = new HashMap();
mapB.put(SRP6KeyAgreement.HASH_FUNCTION, srp.getAlgorithm());
mapB.put(SRP6KeyAgreement.HOST_PASSWORD_DB, authenticator);
try
{
serverHandler.init(mapB);
OutgoingMessage out = new OutgoingMessage();
out.writeString(U);
IncomingMessage in = new IncomingMessage(out.toByteArray());
out = serverHandler.processMessage(in);
in = new IncomingMessage(out.toByteArray());
N = in.readMPI();
g = in.readMPI();
s = in.readMPI().toByteArray();
B = in.readMPI();
}
catch (KeyAgreementException x)
{
throw new SaslException("sendProtocolElements()", x);
}
// -------------------------------------------------------------------
if (Configuration.DEBUG)
{
log.fine("Encoding N (modulus): " + Util.dump(N));
log.fine("Encoding g (generator): " + Util.dump(g));
log.fine("Encoding s (client's salt): " + Util.dumpString(s));
log.fine("Encoding B (server ephemeral public key): " + Util.dump(B));
}
// The server creates an options list (L), which consists of a
// comma-separated list of option strings that specify the security
// service options the server supports.
L = createL();
if (Configuration.DEBUG)
{
log.fine("Encoding L (available options): \"" + L + "\"");
log.fine("Encoding sIV (server IV): " + Util.dumpString(sIV));
}
final OutputBuffer frameOut = new OutputBuffer();
try
{
frameOut.setScalar(1, 0x00);
frameOut.setMPI(N);
frameOut.setMPI(g);
frameOut.setOS(s);
frameOut.setMPI(B);
frameOut.setText(L);
}
catch (IOException x)
{
if (x instanceof SaslException)
throw (SaslException) x;
throw new AuthenticationException("sendProtocolElements()", x);
}
final byte[] result = frameOut.encode();
if (Configuration.DEBUG)
{
log.fine("New session...");
log.fine("S: " + Util.dumpString(result));
log.fine(" N = 0x" + N.toString(16));
log.fine(" g = 0x" + g.toString(16));
log.fine(" s = " + Util.dumpString(s));
log.fine(" B = 0x" + B.toString(16));
log.fine(" L = " + L);
log.exiting(this.getClass().getName(), "sendProtocolElements");
}
return result;
}
}
private byte[] sendEvidence(final byte[] input) throws SaslException
{
if (Configuration.DEBUG)
{
log.entering(this.getClass().getName(), "sendEvidence");
log.fine("C: " + Util.dumpString(input));
}
// Client send A, M1, o, cIV
final InputBuffer frameIn = new InputBuffer(input);
final byte[] M1;
try
{
A = frameIn.getMPI(); // Extract client's ephemeral public key
if (Configuration.DEBUG)
log.fine("Got A (client ephemeral public key): " + Util.dump(A));
M1 = frameIn.getOS(); // Extract evidence
if (Configuration.DEBUG)
log.fine("Got M1 (client evidence): " + Util.dumpString(M1));
o = frameIn.getText(); // Extract client's options list
if (Configuration.DEBUG)
log.fine("Got o (client chosen options): \"" + o + "\"");
cIV = frameIn.getOS(); // Extract client's IV
if (Configuration.DEBUG)
log.fine("Got cIV (client IV): " + Util.dumpString(cIV));
}
catch (IOException x)
{
diff --git a/classpath-0.98/javax/security/auth/callback/ChoiceCallback.java b/classpath-0.98/javax/security/auth/callback/ChoiceCallback.java
index 2398057..c46645d 100644
--- a/classpath-0.98/javax/security/auth/callback/ChoiceCallback.java
+++ b/classpath-0.98/javax/security/auth/callback/ChoiceCallback.java
@@ -1,238 +1,239 @@
/* ChoiceCallback.java -- callback for a choice of values.
Copyright (C) 2003, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.auth.callback;
import java.io.Serializable;
import javax.security.auth.callback.Callback;
/**
* Underlying security services instantiate and pass a
* <code>ChoiceCallback</code> to the <code>handle()</code> method of a
* {@link CallbackHandler} to display a list of choices and to retrieve the
* selected choice(s).
*
* @see CallbackHandler
*/
public class ChoiceCallback implements Callback, Serializable
{
// Constants and variables
// -------------------------------------------------------------------------
/**
* @serial
* @since 1.4
*/
private String prompt;
/**
* @serial the list of choices.
* @since 1.4
*/
private String[] choices;
/**
* @serial the choice to be used as the default choice.
* @since 1.4
*/
private int defaultChoice;
/**
* @serial whether multiple selections are allowed from the list of choices.
* @since 1.4
*/
private boolean multipleSelectionsAllowed;
/**
* @serial the selected choices, represented as indexes into the choices list.
* @since 1.4
*/
private int[] selections;
// Constructor(s)
//--------------------------------------------------------------------------
/**
* Construct a <code>ChoiceCallback</code> with a prompt, a list of choices,
* a default choice, and a boolean specifying whether or not multiple
* selections from the list of choices are allowed.
*
* @param prompt the prompt used to describe the list of choices.
* @param choices the list of choices.
* @param defaultChoice the choice to be used as the default choice when the
* list of choices are displayed. This value is represented as an index into
* the <code>choices</code> array.
* @param multipleSelectionsAllowed boolean specifying whether or not
* multiple selections can be made from the list of choices.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>,
* if <code>prompt</code> has a length of <code>0</code>, if <code>choices</code>
* is <code>null</code>, if <code>choices</code> has a length of <code>0</code>,
* if any element from <code>choices</code> is <code>null</code>, if any
* element from <code>choices</code> has a length of <code>0</code> or if
* <code>defaultChoice</code> does not fall within the array boundaries of
* <code>choices</code>.
*/
public ChoiceCallback(String prompt, String[] choices, int defaultChoice,
boolean multipleSelectionsAllowed)
{
super();
setPrompt(prompt);
setChoices(choices);
if (defaultChoice < 0 || defaultChoice >= this.choices.length)
{
throw new IllegalArgumentException("default choice is out of bounds");
}
this.defaultChoice = defaultChoice;
this.multipleSelectionsAllowed = multipleSelectionsAllowed;
}
// Instance methods
// -------------------------------------------------------------------------
/**
* Get the prompt.
*
* @return the prompt.
*/
public String getPrompt()
{
return prompt;
}
/**
* Get the list of choices.
*
* @return the list of choices.
*/
public String[] getChoices()
{
return choices;
}
/**
* Get the defaultChoice.
*
* @return the defaultChoice, represented as an index into the choices list.
*/
public int getDefaultChoice()
{
return defaultChoice;
}
/**
* Get the boolean determining whether multiple selections from the choices
* list are allowed.
*
* @return whether multiple selections are allowed.
*/
public boolean allowMultipleSelections()
{
return multipleSelectionsAllowed;
}
/**
* Set the selected choice.
*
* @param selection the selection represented as an index into the choices
* list.
* @see #getSelectedIndexes()
*/
public void setSelectedIndex(int selection)
{
this.selections = new int[1];
this.selections[0] = selection;
}
/**
* Set the selected choices.
*
* @param selections the selections represented as indexes into the choices
* list.
* @throws UnsupportedOperationException if multiple selections are not
* allowed, as determined by <code>allowMultipleSelections</code>.
* @see #getSelectedIndexes()
*/
public void setSelectedIndexes(int[] selections)
{
if (!multipleSelectionsAllowed)
{
throw new UnsupportedOperationException("not allowed");
}
this.selections = selections;
}
/**
* Get the selected choices.
*
* @return the selected choices, represented as indexes into the choices list.
* @see #setSelectedIndexes(int[])
*/
public int[] getSelectedIndexes()
{
return selections;
}
private void setPrompt(String prompt) throws IllegalArgumentException
{
if ((prompt == null) || (prompt.length() == 0))
{
throw new IllegalArgumentException("invalid prompt");
}
this.prompt = prompt;
}
private void setChoices(String[] choices) throws IllegalArgumentException
{
if (choices == null || choices.length == 0)
{
throw new IllegalArgumentException("invalid choices");
}
for (int i = 0; i < choices.length; i++)
{
if (choices[i] == null || choices[i].length() == 0)
{
throw new IllegalArgumentException("invalid choice at index #"+i);
}
}
this.choices = choices;
}
}
diff --git a/classpath-0.98/javax/security/auth/callback/NameCallback.java b/classpath-0.98/javax/security/auth/callback/NameCallback.java
index 5ff5e7c..d0d0119 100644
--- a/classpath-0.98/javax/security/auth/callback/NameCallback.java
+++ b/classpath-0.98/javax/security/auth/callback/NameCallback.java
@@ -1,180 +1,181 @@
/* NameCallback.java -- callback for user names.
Copyright (C) 2003, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.auth.callback;
import java.io.Serializable;
import javax.security.auth.callback.Callback;
/**
* Underlying security services instantiate and pass a <code>NameCallback</code>
* to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve
* name information.
*
* @see CallbackHandler
*/
public class NameCallback implements Callback, Serializable
{
// Constants and variables
// -------------------------------------------------------------------------
/**
* @serial
* @since 1.4
*/
private String prompt;
/**
* @serial
* @since 1.4
*/
private String defaultName;
/**
* @serial
* @since 1.4
*/
private String inputName;
// Constructor(s)
// -------------------------------------------------------------------------
/**
* Construct a <code>NameCallback</code> with a prompt.
*
* @param prompt the prompt used to request the name.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
* or if <code>prompt</code> has a length of <code>0</code>.
*/
public NameCallback(String prompt)
{
super();
setPrompt(prompt);
}
/**
* Construct a <code>NameCallback</code> with a prompt and default name.
*
* @param prompt the prompt used to request the information.
* @param defaultName the name to be used as the default name displayed with
* the prompt.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
* or if <code>prompt</code> has a length of <code>0</code>, if
* <code>defaultName</code> is <code>null</code>, or if <code>defaultName</code>
* has a length of <code>0</code>.
*/
public NameCallback(String prompt, String defaultName)
throws IllegalArgumentException
{
super();
setPrompt(prompt);
setDefaultName(defaultName);
}
// Class methods
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
/**
* Get the prompt.
*
* @return the prompt.
*/
public String getPrompt()
{
return prompt;
}
/**
* Get the default name.
*
* @return the default name, or <code>null</code> if this
* <code>NameCallback</code> was not instantiated with a
* <code>defaultName</code>.
*/
public String getDefaultName()
{
return defaultName;
}
/**
* Set the retrieved name.
*
* @param name the retrieved name (which may be <code>null</code>).
* @see #getName()
*/
public void setName(String name)
{
this.inputName = name;
}
/**
* Get the retrieved name.
*
* @return the retrieved name (which may be <code>null</code>)
* @see #setName(String)
*/
public String getName()
{
return inputName;
}
private void setPrompt(String prompt) throws IllegalArgumentException
{
if ((prompt == null) || (prompt.length() == 0))
{
throw new IllegalArgumentException("invalid prompt");
}
this.prompt = prompt;
}
private void setDefaultName(String defaultName) throws IllegalArgumentException
{
if ((defaultName == null) || (defaultName.length() == 0))
{
throw new IllegalArgumentException("invalid default name");
}
this.defaultName = defaultName;
}
}
diff --git a/classpath-0.98/javax/security/auth/callback/TextInputCallback.java b/classpath-0.98/javax/security/auth/callback/TextInputCallback.java
index 37d6da0..dd7a8fe 100644
--- a/classpath-0.98/javax/security/auth/callback/TextInputCallback.java
+++ b/classpath-0.98/javax/security/auth/callback/TextInputCallback.java
@@ -1,179 +1,180 @@
/* TextInputCallback.java -- callbacks for user input.
Copyright (C) 2003, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.auth.callback;
import java.io.Serializable;
import javax.security.auth.callback.Callback;
/**
* Underlying security services instantiate and pass a <code>TextInputCallback</code>
* to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve
* generic text information.
*
* @see CallbackHandler
*/
public class TextInputCallback implements Callback, Serializable
{
// Constants and variables
// -------------------------------------------------------------------------
/**
* @serial
* @since 1.4
*/
private String prompt;
/**
* @serial
* @since 1.4
*/
private String defaultText;
/**
* @serial
* @since 1.4
*/
private String inputText;
// Constructor(s)
// -------------------------------------------------------------------------
/**
* Construct a <code>TextInputCallback</code> with a prompt.
*
* @param prompt the prompt used to request the information.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
* or if <code>prompt</code> has a length of <code>0</code>.
*/
public TextInputCallback(String prompt) throws IllegalArgumentException
{
super();
setPrompt(prompt);
}
/**
* Construct a <code>TextInputCallback</code> with a prompt and default
* input value.
*
* @param prompt the prompt used to request the information.
* @param defaultText the text to be used as the default text displayed with
* the prompt.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>,
* if <code>prompt</code> has a length of <code>0</code>, if
* <code>defaultText</code> is <code>null</code> or if <code>defaultText</code>
* has a length of <code>0</code>.
*/
public TextInputCallback(String prompt, String defaultText)
throws IllegalArgumentException
{
super();
setPrompt(prompt);
setDefaultText(defaultText);
}
// Class methods
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
/**
* Get the prompt.
*
* @return the prompt.
*/
public String getPrompt()
{
return prompt;
}
/**
* Get the default text.
*
* @return the default text, or <code>null</code> if this
* <code>TextInputCallback</code> was not instantiated with
* <code>defaultText</code>.
*/
public String getDefaultText()
{
return defaultText;
}
/**
* Set the retrieved text.
*
* @param text the retrieved text, which may be <code>null</code>.
*/
public void setText(String text)
{
this.inputText = text;
}
/**
* Get the retrieved text.
*
* @return the retrieved text, which may be <code>null</code>.
*/
public String getText()
{
return inputText;
}
private void setPrompt(String prompt) throws IllegalArgumentException
{
if ((prompt == null) || (prompt.length() == 0))
{
throw new IllegalArgumentException("invalid prompt");
}
this.prompt = prompt;
}
private void setDefaultText(String defaultText) throws IllegalArgumentException
{
if ((defaultText == null) || (defaultText.length() == 0))
{
throw new IllegalArgumentException("invalid default text");
}
this.defaultText = defaultText;
}
}
diff --git a/classpath-0.98/javax/security/sasl/AuthenticationException.java b/classpath-0.98/javax/security/sasl/AuthenticationException.java
index dff1bd0..64f2594 100644
--- a/classpath-0.98/javax/security/sasl/AuthenticationException.java
+++ b/classpath-0.98/javax/security/sasl/AuthenticationException.java
@@ -1,107 +1,108 @@
/* AuthenticationException.java --
Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
/**
* <p>This exception is thrown by a SASL mechanism implementation to indicate
* that the SASL exchange has failed due to reasons related to authentication,
* such as an invalid identity, passphrase, or key.</p>
*
* <p>Note that the lack of an <code>AuthenticationException</code> does not
* mean that the failure was not due to an authentication error. A SASL
* mechanism implementation might throw the more general {@link SaslException}
* instead of <code>AuthenticationException</code> if it is unable to determine
* the nature of the failure, or if does not want to disclose the nature of the
* failure, for example, due to security reasons.</p>
*
* @since 1.5
*/
public class AuthenticationException extends SaslException
{
// Constants and variables
// -------------------------------------------------------------------------
// Constructor(s)
// -------------------------------------------------------------------------
/**
* Constructs a new instance of <code>AuthenticationException</code>. The
* root exception and the detailed message are <code>null</code>.
*/
public AuthenticationException()
{
super();
}
/**
* Constructs a new instance of <code>AuthenticationException</code> with a
* detailed message. The root exception is <code>null</code>.
*
* @param detail a possibly <code>null</code> string containing details of
* the exception.
* @see Throwable#getMessage()
*/
public AuthenticationException(String detail)
{
super(detail);
}
/**
* Constructs a new instance of <code>AuthenticationException</code> with a
* detailed message and a root exception.
*
* @param detail a possibly <code>null</code> string containing details of
* the exception.
* @param ex a possibly <code>null</code> root exception that caused this
* exception.
* @see Throwable#getMessage()
* @see SaslException#getCause()
*/
public AuthenticationException(String detail, Throwable ex)
{
super(detail, ex);
}
// Class methods
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
}
diff --git a/classpath-0.98/javax/security/sasl/RealmCallback.java b/classpath-0.98/javax/security/sasl/RealmCallback.java
index 9913cf7..ab2b828 100644
--- a/classpath-0.98/javax/security/sasl/RealmCallback.java
+++ b/classpath-0.98/javax/security/sasl/RealmCallback.java
@@ -1,77 +1,78 @@
/* RealmCallback.java --
Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
import gnusasl.javax.security.auth.callback.TextInputCallback;
/**
* This callback is used by {@link SaslClient} and {@link SaslServer} to
* retrieve realm information.
*
* @since 1.5
*/
public class RealmCallback extends TextInputCallback
{
/**
* Constructs a <code>RealmCallback</code> with a prompt.
*
* @param prompt the non-null prompt to use to request the realm information.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
* or empty.
*/
public RealmCallback(String prompt)
{
super(prompt);
}
/**
* Constructs a <code>RealmCallback</code> with a prompt and default realm
* information.
*
* @param prompt the non-null prompt to use to request the realm information.
* @param defaultRealmInfo the non-null default realm information to use.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
* or empty, or if <code>defaultRealm</code> is empty or <code>null</code>.
*/
public RealmCallback(String prompt, String defaultRealmInfo)
{
super(prompt, defaultRealmInfo);
}
}
diff --git a/classpath-0.98/javax/security/sasl/RealmChoiceCallback.java b/classpath-0.98/javax/security/sasl/RealmChoiceCallback.java
index 56ec8fc..63767cb 100644
--- a/classpath-0.98/javax/security/sasl/RealmChoiceCallback.java
+++ b/classpath-0.98/javax/security/sasl/RealmChoiceCallback.java
@@ -1,73 +1,74 @@
/* RealmChoiceCallback.java --
Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
import gnusasl.javax.security.auth.callback.ChoiceCallback;
/**
* This callback is used by {@link SaslClient} and {@link SaslServer} to obtain
* a realm given a list of realm choices.
*
* @since 1.5
*/
public class RealmChoiceCallback extends ChoiceCallback
{
/**
* Constructs a <code>RealmChoiceCallback</code> with a prompt, a list of
* choices and a default choice.
*
* @param prompt the non-null prompt to use to request the realm.
* @param choices the non-null list of realms to choose from.
* @param defaultChoice the choice to be used as the default when the list of
* choices is displayed. It is an index into the <code>choices</code> array.
* @param multiple <code>true</code> if multiple choices allowed;
* <code>false</code> otherwise.
* @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
* or empty, if <code>choices</code> has a length of <code>0</code>, if any
* element from <code>choices</code> is <code>null</code> or empty, or if
* <code>defaultChoice</code> does not fall within the array boundary of
* <code>choices</code>.
*/
public RealmChoiceCallback(String prompt, String[] choices, int defaultChoice,
boolean multiple)
{
super(prompt, choices, defaultChoice, multiple);
}
}
diff --git a/classpath-0.98/javax/security/sasl/Sasl.java b/classpath-0.98/javax/security/sasl/Sasl.java
index e9a4698..9a492a0 100644
--- a/classpath-0.98/javax/security/sasl/Sasl.java
+++ b/classpath-0.98/javax/security/sasl/Sasl.java
@@ -1,514 +1,515 @@
/* Sasl.java --
Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
import java.security.Provider;
import java.security.Security;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import javax.security.auth.callback.CallbackHandler;
/**
* <p>A static class for creating SASL clients and servers.</p>
*
* <p>This class defines the policy of how to locate, load, and instantiate SASL
* clients and servers.</p>
*
* <p>For example, an application or library gets a SASL client instance by
* doing something like:</p>
*
* <pre>
*SaslClient sc =
* Sasl.createSaslClient(mechanisms, authorizationID, protocol,
* serverName, props, callbackHandler);
* </pre>
*
* <p>It can then proceed to use the instance to create an authenticated
* connection.</p>
*
* <p>Similarly, a server gets a SASL server instance by using code that looks
* as follows:</p>
*
* <pre>
*SaslServer ss =
* Sasl.createSaslServer(mechanism, protocol, serverName, props,
* callbackHandler);
* </pre>
*
* @since 1.5
*/
public class Sasl
{
// Constants and variables
// -------------------------------------------------------------------------
/**
* <p>The name of a property that specifies the quality-of-protection to use.
* The property contains a comma-separated, ordered list of quality-of-
* protection values that the client or server is willing to support. A qop
* value is one of:</p>
*
* <ul>
* <li><code>"auth"</code> - authentication only,</li>
* <li><code>"auth-int"</code> - authentication plus integrity
* protection,</li>
* <li><code>"auth-conf"</code> - authentication plus integrity and
* confidentiality protection.</li>
* </ul>
*
* <p>The order of the list specifies the preference order of the client or
* server.</p>
*
* <p>If this property is absent, the default qop is <code>"auth"</code>.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.qop"</code>.</p>
*/
public static final String QOP = "javax.security.sasl.qop";
/**
* <p>The name of a property that specifies the cipher strength to use. The
* property contains a comma-separated, ordered list of cipher strength
* values that the client or server is willing to support. A strength value
* is one of:</p>
*
* <ul>
* <li><code>"low"</code>,</li>
* <li><code>"medium"</code>,</li>
* <li><code>"high"</code>.</li>
* </ul>
*
* <p>The order of the list specifies the preference order of the client or
* server. An implementation should allow configuration of the meaning of
* these values. An application may use the Java Cryptography Extension (JCE)
* with JCE-aware mechanisms to control the selection of cipher suites that
* match the strength values.</p>
*
* <p>If this property is absent, the default strength is
* <code>"high,medium,low"</code>.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.strength"</code>.
* </p>
*/
public static final String STRENGTH = "javax.security.sasl.strength";
/**
* <p>The name of a property that specifies whether the server must authenticate
* to the client. The property contains <code>"true"</code> if the server
* must authenticate the to client; <code>"false"</code> otherwise. The
* default is <code>"false"</code>.</p>
*
* <p>The value of this constant is
* <code>"javax.security.sasl.server.authentication"</code>.</p>
*/
public static final String SERVER_AUTH = "javax.security.sasl.server.authentication";
/**
* <p>The name of a property that specifies the maximum size of the receive
* buffer in bytes of {@link SaslClient}/{@link SaslServer}. The property
* contains the string representation of an integer.</p>
*
* <p>If this property is absent, the default size is defined by the
* mechanism.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.maxbuffer"</code>.
* </p>
*/
public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";
/**
* <p>The name of a property that specifies the maximum size of the raw send
* buffer in bytes of {@link SaslClient}/{@link SaslServer}. The property
* contains the string representation of an integer. The value of this
* property is negotiated between the client and server during the
* authentication exchange.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.rawsendsize"</code>.
* </p>
*/
public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";
/**
* <p>The name of a property that specifies whether mechanisms susceptible
* to simple plain passive attacks (e.g., "PLAIN") are not permitted. The
* property contains <code>"true"</code> if such mechanisms are not
* permitted; <code>"false"</code> if such mechanisms are permitted. The
* default is <code>"false"</code>.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.policy.noplaintext"</code>.
* </p>
*/
public static final String POLICY_NOPLAINTEXT = "javax.security.sasl.policy.noplaintext";
/**
* <p>The name of a property that specifies whether mechanisms susceptible to
* active (non-dictionary) attacks are not permitted. The property contains
* <code>"true"</code> if mechanisms susceptible to active attacks are not
* permitted; <code>"false"</code> if such mechanisms are permitted. The
* default is <code>"false"</code>.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.policy.noactive"</code>.
* </p>
*/
public static final String POLICY_NOACTIVE = "javax.security.sasl.policy.noactive";
/**
* <p>The name of a property that specifies whether mechanisms susceptible to
* passive dictionary attacks are not permitted. The property contains
* <code>"true"</code> if mechanisms susceptible to dictionary attacks are
* not permitted; <code>"false"</code> if such mechanisms are permitted. The
* default is <code>"false"</code>.</p>
*
* <p>The value of this constant is <code>"javax.security.sasl.policy.nodictionary"</code>.
* </p>
*/
public static final String POLICY_NODICTIONARY = "javax.security.sasl.policy.nodictionary";
/**
* <p>The name of a property that specifies whether mechanisms that accept
* anonymous login are not permitted. The property contains <code>"true"</code>
* if mechanisms that accept anonymous login are not permitted; <code>"false"
* </code> if such mechanisms are permitted. The default is <code>"false"</code>.
* </p>
*
* <p>The value of this constant is <code>"javax.security.sasl.policy.noanonymous"</code>.
* </p>
*/
public static final String POLICY_NOANONYMOUS = "javax.security.sasl.policy.noanonymous";
/**
* The name of a property that specifies whether mechanisms that implement
* forward secrecy between sessions are required. Forward secrecy means that
* breaking into one session will not automatically provide information for
* breaking into future sessions. The property contains <code>"true"</code>
* if mechanisms that implement forward secrecy between sessions are
* required; <code>"false"</code> if such mechanisms are not required. The
* default is <code>"false"</code>.
*
* <p>The value of this constant is <code>"javax.security.sasl.policy.forward"</code>.
* </p>
*/
public static final String POLICY_FORWARD_SECRECY = "javax.security.sasl.policy.forward";
/**
* The name of a property that specifies whether mechanisms that pass client
* credentials are required. The property contains <code>"true"</code> if
* mechanisms that pass client credentials are required; <code>"false"</code>
* if such mechanisms are not required. The default is <code>"false"</code>.
*
* <p>The value of this constant is <code>"javax.security.sasl.policy.credentials"</code>.
* </p>
*/
public static final String POLICY_PASS_CREDENTIALS = "javax.security.sasl.policy.credentials";
/**
* <p>The name of a property that specifies whether to reuse previously
* authenticated session information. The property contains <code>"true"</code>
* if the mechanism implementation may attempt to reuse previously
* authenticated session information; it contains <code>"false"</code> if the
* implementation must not reuse previously authenticated session information.
* A setting of <code>"true"</code> serves only as a hint; it does not
* necessarily entail actual reuse because reuse might not be possible due to
* a number of reasons, including, but not limited to, lack of mechanism
* support for reuse, expiration of reusable information, and the peer's
* refusal to support reuse. The property's default value is <code>"false"</code>.
* </p>
*
* <p>The value of this constant is <code>"javax.security.sasl.reuse"</code>.
* Note that all other parameters and properties required to create a SASL
* client/server instance must be provided regardless of whether this
* property has been supplied. That is, you cannot supply any less
* information in anticipation of reuse. Mechanism implementations that
* support reuse might allow customization of its implementation for factors
* such as cache size, timeouts, and criteria for reuseability. Such
* customizations are implementation-dependent.</p>
*/
public static final String REUSE = "javax.security.sasl.reuse";
private static final String CLIENT_FACTORY_SVC = "SaslClientFactory.";
private static final String SERVER_FACTORY_SVC = "SaslServerFactory.";
private static final String ALIAS = "Alg.Alias.";
// Constructor(s)
// -------------------------------------------------------------------------
private Sasl()
{
super();
}
// Class methods
// -------------------------------------------------------------------------
/**
* Creates a {@link SaslClient} for the specified mechanism.
*
* <p>This method uses the JCA Security Provider Framework, described in the
* "Java Cryptography Architecture API Specification & Reference", for
* locating and selecting a {@link SaslClient} implementation.</p>
*
* <p>First, it obtains an ordered list of {@link SaslClientFactory}
* instances from the registered security providers for the
* <code>"SaslClientFactory"</code> service and the specified mechanism. It
* then invokes <code>createSaslClient()</code> on each factory instance on
* the list until one produces a non-null {@link SaslClient} instance. It
* returns the non-null {@link SaslClient} instance, or <code>null</code> if
* the search fails to produce a non-null {@link SaslClient} instance.</p>
*
* <p>A security provider for <code>SaslClientFactory</code> registers with
* the JCA Security Provider Framework keys of the form:</p>
*
* <pre>
* SaslClientFactory.mechanism_name
* </pre>
*
* <p>and values that are class names of implementations of {@link
* SaslClientFactory}.</p>
*
* <p>For example, a provider that contains a factory class,
* <code>com.wiz.sasl.digest.ClientFactory</code>, that supports the
* <code>"DIGEST-MD5"</code> mechanism would register the following entry
* with the JCA:</p>
*
* <pre>
* SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory
* </pre>
*
* <p>See the "Java Cryptography Architecture API Specification &
* Reference" for information about how to install and configure security
* service providers.</p>
*
* @param mechanisms the non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationID the possibly <code>null</code> protocol-dependent
* identification to be used for authorization. If <code>null</code> or
* empty, the server derives an authorization ID from the client's
* authentication credentials. When the SASL authentication completes
* successfully, the specified entity is granted access.
* @param protocol the non-null string name of the protocol for which the
* authentication is being performed (e.g. "ldap").
* @param serverName the non-null fully-qualified host name of the server to
* authenticate to.
* @param props the possibly null set of properties used to select the SASL
* mechanism and to configure the authentication exchange of the selected
* mechanism. For example, if props contains the {@link Sasl#POLICY_NOPLAINTEXT}
* property with the value <code>"true"</code>, then the selected SASL
* mechanism must not be susceptible to simple plain passive attacks. In
* addition to the standard properties declared in this class, other,
* possibly mechanism-specific, properties can be included. Properties not
* relevant to the selected mechanism are ignored.
* @param cbh the possibly <code>null</code> callback handler to used by the
* SASL mechanisms to get further information from the application/library to
* complete the authentication. For example, a SASL mechanism might require
* the authentication ID, password and realm from the caller. The
* authentication ID is requested by using a
* {@link javax.security.auth.callback.NameCallback}. The password is
* requested by using a {@link javax.security.auth.callback.PasswordCallback}.
* The realm is requested by using a {@link RealmChoiceCallback} if there is
* a list of realms to choose from, and by using a {@link RealmCallback} if
* the realm must be entered.
* @return a possibly <code>null</code> {@link SaslClient} created using the
* parameters supplied. If <code>null</code>, the method could not find a
* {@link SaslClientFactory} that will produce one.
* @throws SaslException if a {@link SaslClient} cannot be created because
* of an error.
*/
public static SaslClient createSaslClient(String[] mechanisms,
String authorizationID,
String protocol,
String serverName,
Map<String, ?> props,
CallbackHandler cbh)
throws SaslException
{
if (mechanisms == null)
{
return null;
}
Provider[] providers = Security.getProviders();
if (providers == null || providers.length == 0)
{
return null;
}
SaslClient result = null;
SaslClientFactory factory = null;
String m, clazz = null, upper, alias;
int j;
Provider p;
for (int i = 0; i < mechanisms.length; i++)
{
m = mechanisms[i];
if (m == null)
continue;
for (j = 0; j < providers.length; j++)
{
p = providers[j];
if (p != null)
{
// try the name as is
clazz = p.getProperty(CLIENT_FACTORY_SVC + m);
if (clazz == null) // try all uppercase
{
upper = m.toUpperCase();
clazz = p.getProperty(CLIENT_FACTORY_SVC + upper);
if (clazz == null) // try if it's an alias
{
alias = p.getProperty(ALIAS + CLIENT_FACTORY_SVC + m);
if (alias == null) // try all-uppercase alias name
{
alias = p.getProperty(ALIAS + CLIENT_FACTORY_SVC + upper);
if (alias == null) // spit the dummy
continue;
}
clazz = p.getProperty(CLIENT_FACTORY_SVC + alias);
}
}
if (clazz == null)
continue;
else
clazz = clazz.trim();
}
try
{
result = null;
factory = (SaslClientFactory) Class.forName(clazz).newInstance();
result = factory.createSaslClient(mechanisms, authorizationID,
protocol, serverName, props, cbh);
}
catch (ClassCastException ignored) // ignore instantiation exceptions
{
}
catch (ClassNotFoundException ignored)
{
}
catch (InstantiationException ignored)
{
}
catch (IllegalAccessException ignored)
{
}
if (result != null)
return result;
}
}
return null;
}
/**
* Gets an enumeration of known factories for producing a {@link SaslClient}
* instance. This method uses the same sources for locating factories as
* <code>createSaslClient()</code>.
*
* @return a non-null {@link Enumeration} of known factories for producing a
* {@link SaslClient} instance.
* @see #createSaslClient(String[],String,String,String,Map,CallbackHandler)
*/
public static Enumeration<SaslClientFactory> getSaslClientFactories()
{
Vector result = new Vector();
HashSet names = new HashSet();
Provider[] providers = Security.getProviders();
Iterator it;
if (providers != null)
{
Provider p;
String key;
for (int i = 0; i < providers.length; i++)
{
p = providers[i];
for (it = p.keySet().iterator(); it.hasNext(); )
{
key = (String) it.next();
// add key's binding (a) it is a class of a client factory,
// and (b) the key does not include blanks
if (key.startsWith(CLIENT_FACTORY_SVC) && key.indexOf(" ") == -1)
{
names.add(p.getProperty(key));
break;
}
}
}
}
// we have the factory class names in names; instantiate and enumerate
String c;
for (it = names.iterator(); it.hasNext(); )
{
c = (String) it.next();
try
{
SaslClientFactory f = (SaslClientFactory) Class.forName(c).newInstance();
if (f != null)
result.add(f);
} catch (ClassCastException ignored) { // ignore instantiation exceptions
} catch (ClassNotFoundException ignored) {
} catch (InstantiationException ignored) {
} catch (IllegalAccessException ignored) {
}
}
return result.elements();
}
/**
* Creates a {@link SaslServer} for the specified mechanism.
*
* <p>This method uses the JCA Security Provider Framework, described in the
* "Java Cryptography Architecture API Specification & Reference", for
* locating and selecting a SaslServer implementation.</p>
*
* <p>First, it obtains an ordered list of {@link SaslServerFactory}
* instances from the registered security providers for the
* <code>"SaslServerFactory"</code> service and the specified mechanism. It
* then invokes <code>createSaslServer()</code> on each factory instance on
* the list until one produces a non-null {@link SaslServer} instance. It
* returns the non-null {@link SaslServer} instance, or <code>null</code> if
* the search fails to produce a non-null {@link SaslServer} instance.</p>
*
* <p>A security provider for {@link SaslServerFactory} registers with the
* JCA Security Provider Framework keys of the form:</p>
*
* <pre>
* SaslServerFactory.mechanism_name
* </pre>
diff --git a/classpath-0.98/javax/security/sasl/SaslClient.java b/classpath-0.98/javax/security/sasl/SaslClient.java
index ada4d0b..4c2f6f6 100644
--- a/classpath-0.98/javax/security/sasl/SaslClient.java
+++ b/classpath-0.98/javax/security/sasl/SaslClient.java
@@ -1,232 +1,233 @@
/* SaslClient.java --
Copyright (C) 2003, 2004, 2005 Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
/**
* <p>Performs SASL authentication as a client.</p>
*
* <p>A protocol library such as one for LDAP gets an instance of this class in
* order to perform authentication defined by a specific SASL mechanism.
* Invoking methods on the <code>SaslClient</code> instance process challenges
* and create responses according to the SASL mechanism implemented by the
* <code>SaslClient</code>. As the authentication proceeds, the instance
* encapsulates the state of a SASL client's authentication exchange.</p>
*
* <p>Here's an example of how an LDAP library might use a <code>SaslClient</code>.
* It first gets an instance of a SaslClient:</p>
* <pre>
*SaslClient sc =
* Sasl.createSaslClient(mechanisms, authorizationID, protocol,
* serverName, props, callbackHandler);
* </pre>
*
* <p>It can then proceed to use the client for authentication. For example, an
* LDAP library might use the client as follows:</p>
* <pre>
* // Get initial response and send to server
*byte[] response = sc.hasInitialResponse()
* ? sc.evaluateChallenge(new byte[0]) : null;
*LdapResult res = ldap.sendBindRequest(dn, sc.getName(), response);
*while (!sc.isComplete()
* && ((res.status == SASL_BIND_IN_PROGRESS) || (res.status == SUCCESS))) {
* response = sc.evaluateChallenge( res.getBytes() );
* if (res.status == SUCCESS) {
* // we're done; don't expect to send another BIND
* if ( response != null ) {
* throw new SaslException(
* "Protocol error: attempting to send response after completion");
* }
* break;
* }
* res = ldap.sendBindRequest(dn, sc.getName(), response);
*}
*if (sc.isComplete() && (res.status == SUCCESS) ) {
* String qop = (String)sc.getNegotiatedProperty(Sasl.QOP);
* if ((qop != null)
* && (qop.equalsIgnoreCase("auth-int")
* || qop.equalsIgnoreCase("auth-conf"))) {
* // Use SaslClient.wrap() and SaslClient.unwrap() for future
* // communication with server
* ldap.in = new SecureInputStream(sc, ldap.in);
* ldap.out = new SecureOutputStream(sc, ldap.out);
* }
*}
* </pre>
*
* <p>If the mechanism has an initial response, the library invokes
* {@link #evaluateChallenge(byte[])} with an empty challenge to get the initial
* response. Protocols such as IMAP4, which do not include an initial response
* with their first authentication command to the server, initiate the
* authentication without first calling {@link #hasInitialResponse()} or
* {@link #evaluateChallenge(byte[])}. When the server responds to the command,
* it sends an initial challenge. For a SASL mechanism in which the client sends
* data first, the server should have issued a challenge with no data. This will
* then result in a call (on the client) to {@link #evaluateChallenge(byte[])}
* with an empty challenge.</p>
*
* @see Sasl
* @see SaslClientFactory
*
* @since 1.5
*/
public interface SaslClient
{
/**
* Returns the IANA-registered mechanism name of this SASL client. (e.g.
* "CRAM-MD5", "GSSAPI").
*
* @return a non-null string representing the IANA-registered mechanism name.
*/
String getMechanismName();
/**
* Determines if this mechanism has an optional initial response. If
* <code>true</code>, caller should call {@link #evaluateChallenge(byte[])}
* with an empty array to get the initial response.
*
* @return <code>true</code> if this mechanism has an initial response.
*/
boolean hasInitialResponse();
/**
* Evaluates the challenge data and generates a response. If a challenge is
* received from the server during the authentication process, this method is
* called to prepare an appropriate next response to submit to the server.
*
* @param challenge the non-null challenge sent from the server. The
* challenge array may have zero length.
* @return the possibly <code>null</code> reponse to send to the server. It
* is <code>null</code> if the challenge accompanied a "SUCCESS" status and
* the challenge only contains data for the client to update its state and no
* response needs to be sent to the server. The response is a zero-length
* byte array if the client is to send a response with no data.
* @throws SaslException if an error occurred while processing the challenge
* or generating a response.
*/
byte[] evaluateChallenge(byte[] challenge) throws SaslException;
/**
* Determines if the authentication exchange has completed. This method may
* be called at any time, but typically, it will not be called until the
* caller has received indication from the server (in a protocol-specific
* manner) that the exchange has completed.
*
* @return <code>true</code> if the authentication exchange has completed;
* <code>false</code> otherwise.
*/
boolean isComplete();
/**
* <p>Unwraps a byte array received from the server. This method can be
* called only after the authentication exchange has completed (i.e., when
* {@link #isComplete()} returns <code>true</code>) and only if the
* authentication exchange has negotiated integrity and/or privacy as the
* quality of protection; otherwise, an {@link IllegalStateException} is
* thrown.</p>
*
* <p><code>incoming</code> is the contents of the SASL buffer as defined in
* RFC 2222 without the leading four octet field that represents the length.
* <code>offset</code> and <code>len</code> specify the portion of incoming
* to use.</p>
*
* @param incoming a non-null byte array containing the encoded bytes from
* the server.
* @param offset the starting position at <code>incoming</code> of the bytes
* to use.
* @param len the number of bytes from <code>incoming</code> to use.
* @return a non-null byte array containing the decoded bytes.
* @throws SaslException if <code>incoming</code> cannot be successfully
* unwrapped.
* @throws IllegalStateException if the authentication exchange has not
* completed, or if the negotiated quality of protection has neither
* integrity nor privacy.
*/
byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException;
/**
* <p>Wraps a byte array to be sent to the server. This method can be called
* only after the authentication exchange has completed (i.e., when
* {@link #isComplete()} returns <code>true</code>) and only if the
* authentication exchange has negotiated integrity and/or privacy as the
* quality of protection; otherwise, an {@link IllegalStateException} is
* thrown.</p>
*
* <p>The result of this method will make up the contents of the SASL buffer
* as defined in RFC 2222 without the leading four octet field that
* represents the length. <code>offset</code> and <code>len</code> specify
* the portion of <code>outgoing</code> to use.</p>
*
* @param outgoing a non-null byte array containing the bytes to encode.
* @param offset the starting position at <code>outgoing</code> of the bytes
* to use.
* @param len the number of bytes from <code>outgoing</code> to use.
* @return a non-null byte array containing the encoded bytes.
* @throws SaslException if <code>outgoing</code> cannot be successfully
* wrapped.
* @throws IllegalStateException if the authentication exchange has not
* completed, or if the negotiated quality of protection has neither
* integrity nor privacy.
*/
byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException;
/**
* Retrieves the negotiated property. This method can be called only after
* the authentication exchange has completed (i.e., when {@link #isComplete()}
* returns <code>true</code>); otherwise, an {@link IllegalStateException} is
* thrown.
*
* @param propName the non-null property name.
* @return the value of the negotiated property. If <code>null</code>, the
* property was not negotiated or is not applicable to this mechanism.
* @throws IllegalStateException if this authentication exchange has not
* completed.
*/
Object getNegotiatedProperty(String propName);
/**
* Disposes of any system resources or security-sensitive information the
* <code>SaslClient</code> might be using. Invoking this method invalidates
* the <code>SaslClient</code> instance. This method is idempotent.
*
* @throws SaslException if a problem was encountered while disposing of the
* resources.
*/
void dispose() throws SaslException;
}
diff --git a/classpath-0.98/javax/security/sasl/SaslClientFactory.java b/classpath-0.98/javax/security/sasl/SaslClientFactory.java
index 9625aae..c4af6a5 100644
--- a/classpath-0.98/javax/security/sasl/SaslClientFactory.java
+++ b/classpath-0.98/javax/security/sasl/SaslClientFactory.java
@@ -1,118 +1,119 @@
/* SaslClientFactory.java
Copyright (C) 2003, 2005, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* <p>An interface for creating instances of {@link SaslClient}. A class that
* implements this interface must be thread-safe and handle multiple
* simultaneous requests. It must also have a public constructor that accepts
* no arguments.</p>
*
* <p>This interface is not normally accessed directly by a client, which will
* use the {@link Sasl} static methods to create a client instance instead.
* However, a particular environment may provide and install a new or different
* <code>SaslClientFactory</code>.</p>
*
* @see SaslClient
* @see Sasl
*
* @since 1.5
*/
public interface SaslClientFactory
{
/**
* Creates a {@link SaslClient} using the parameters supplied.
*
* @param mechanisms the non-null list of mechanism names to try. Each is the
* IANA-registered name of a SASL mechanism (e.g. "GSSAPI", "CRAM-MD5").
* @param authorizationID the possibly null protocol-dependent identification
* to be used for authorization. If <code>null</code> or empty, the server
* derives an authorization ID from the client's authentication credentials.
* When the SASL authentication completes successfully, the specified entity
* is granted access.
* @param protocol the non-null string name of the protocol for which the
* authentication is being performed (e.g. "ldap").
* @param serverName the non-null fully qualified host name of the server to
* authenticate to.
* @param props the possibly <code>null</code> set of properties used to
* select the SASL mechanism and to configure the authentication exchange of
* the selected mechanism. See the {@link Sasl} class for a list of standard
* properties. Other, possibly mechanism-specific, properties can be included.
* Properties not relevant to the selected mechanism are ignored.
* @param cbh the possibly <code>null</code> callback handler to used by the
* SASL mechanisms to get further information from the application/library to
* complete the authentication. For example, a SASL mechanism might require
* the authentication ID, password and realm from the caller. The
* authentication ID is requested by using a
* {@link javax.security.auth.callback.NameCallback}. The password is
* requested by using a {@link javax.security.auth.callback.PasswordCallback}.
* The realm is requested by using a {@link RealmChoiceCallback} if there is
* a list of realms to choose from, and by using a {@link RealmCallback} if
* the realm must be entered.
* @return a possibly <code>null</code> {@link SaslClient} created using the
* parameters supplied. If <code>null</code>, this factory cannot produce a
* {@link SaslClient} using the parameters supplied.
* @throws SaslException if a {@link SaslClient} instance cannot be created
* because of an error.
*/
SaslClient createSaslClient(String[] mechanisms, String authorizationID,
String protocol, String serverName,
Map<String, ?> props, CallbackHandler cbh)
throws SaslException;
/**
* Returns an array of names of mechanisms that match the specified mechanism
* selection policies.
*
* @param props the possibly <code>null</code> set of properties used to
* specify the security policy of the SASL mechanisms. For example, if props
* contains the {@link Sasl#POLICY_NOPLAINTEXT} property with the value
* <code>"true"</code>, then the factory must not return any SASL mechanisms
* that are susceptible to simple plain passive attacks. See the {@link Sasl}
* class for a complete list of policy properties. Non-policy related
* properties, if present in props, are ignored.
* @return a non-null array containing IANA-registered SASL mechanism names.
*/
String[] getMechanismNames(Map<String, ?> props);
}
diff --git a/classpath-0.98/javax/security/sasl/SaslException.java b/classpath-0.98/javax/security/sasl/SaslException.java
index e494d1f..28d3fec 100644
--- a/classpath-0.98/javax/security/sasl/SaslException.java
+++ b/classpath-0.98/javax/security/sasl/SaslException.java
@@ -1,189 +1,190 @@
/* SaslException.java
Copyright (C) 2003, 2005, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
import gnu.java.lang.CPStringBuilder;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Serializable;
/**
* This class represents an error that has occurred when using SASL.
*
* @since 1.5
*/
public class SaslException extends IOException implements Serializable
{
// Constants and variables
// -------------------------------------------------------------------------
private static final long serialVersionUID = 4579784287983423626L;
/**
* @serial The possibly null root cause exception.
*/
private Throwable _exception = null;
// Constructor(s)
// -------------------------------------------------------------------------
/**
* Constructs a new instance of <code>SaslException</code>. The root
* exception and the detailed message are null.
*/
public SaslException()
{
super();
}
/**
* Constructs a new instance of <code>SaslException</code> with a detailed
* message. The <code>root</code> exception is <code>null</code>.
*
* @param detail a possibly null string containing details of the exception.
* @see Throwable#getMessage()
*/
public SaslException(String detail)
{
super(detail);
}
/**
* Constructs a new instance of <code>SaslException</code> with a detailed
* message and a root exception. For example, a <code>SaslException</code>
* might result from a problem with the callback handler, which might throw a
* {@link javax.security.auth.callback.UnsupportedCallbackException} if it
* does not support the requested callback, or throw an {@link IOException}
* if it had problems obtaining data for the callback. The
* <code>SaslException</code>'s root exception would be then be the exception
* thrown by the callback handler.
*
* @param detail a possibly <code>null</code> string containing details of
* the exception.
* @param ex a possibly <code>null</code> root exception that caused this
* exception.
* @see Throwable#getMessage()
* @see #getCause()
*/
public SaslException(String detail, Throwable ex)
{
super(detail);
_exception = ex;
}
// Class methods
// -------------------------------------------------------------------------
// Instance methods
// -------------------------------------------------------------------------
/**
* Returns the cause of this throwable or <code>null</code> if the cause is
* nonexistent or unknown. The cause is the throwable that caused this
* exception to be thrown.
*
* @return the possibly <code>null</code> exception that caused this exception.
*/
public Throwable getCause()
{
return _exception;
}
/**
* Prints this exception's stack trace to <code>System.err</code>. If this
* exception has a root exception; the stack trace of the root exception is
* also printed to <code>System.err</code>.
*/
public void printStackTrace()
{
super.printStackTrace();
if (_exception != null)
_exception.printStackTrace();
}
/**
* Prints this exception's stack trace to a print stream. If this exception
* has a root exception; the stack trace of the root exception is also
* printed to the print stream.
*
* @param ps the non-null print stream to which to print.
*/
public void printStackTrace(PrintStream ps)
{
super.printStackTrace(ps);
if (_exception != null)
_exception.printStackTrace(ps);
}
/**
* Prints this exception's stack trace to a print writer. If this exception
* has a root exception; the stack trace of the root exception is also
* printed to the print writer.
*
* @param pw the non-null print writer to use for output.
*/
public void printStackTrace(PrintWriter pw)
{
super.printStackTrace(pw);
if (_exception != null)
_exception.printStackTrace(pw);
}
/**
* Returns the string representation of this exception. The string
* representation contains this exception's class name, its detailed
* messsage, and if it has a root exception, the string representation of the
* root exception. This string representation is meant for debugging and not
* meant to be interpreted programmatically.
*
* @return the non-null string representation of this exception.
* @see Throwable#getMessage()
*/
public String toString()
{
CPStringBuilder sb = new CPStringBuilder(this.getClass().getName())
.append(": ").append(super.toString());
if (_exception != null)
sb.append("; caused by: ").append(_exception.toString());
return sb.toString();
}
}
diff --git a/classpath-0.98/javax/security/sasl/SaslServer.java b/classpath-0.98/javax/security/sasl/SaslServer.java
index 0a4f223..e632e25 100644
--- a/classpath-0.98/javax/security/sasl/SaslServer.java
+++ b/classpath-0.98/javax/security/sasl/SaslServer.java
@@ -1,227 +1,228 @@
/* SaslServer.java
Copyright (C) 2003, 2005, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
/**
* <p>Performs SASL authentication as a server.</p>
*
* <p>A server such as an LDAP server gets an instance of this class in order to
* perform authentication defined by a specific SASL mechanism. Invoking methods
* on the <code>SaslServer</code> instance generates challenges corresponding to
* the SASL mechanism implemented by the <code>SaslServer</code> instance. As
* the authentication proceeds, the instance encapsulates the state of a SASL
* server's authentication exchange.</p>
*
* <p>Here's an example of how an LDAP server might use a <code>SaslServer</code>
* instance. It first gets an instance of a <code>SaslServer</code> for the SASL
* mechanism requested by the client:</p>
*
* <pre>
*SaslServer ss =
* Sasl.createSaslServer(mechanism, "ldap", myFQDN, props, callbackHandler);
* </pre>
*
* <p>It can then proceed to use the server for authentication. For example,
* suppose the LDAP server received an LDAP BIND request containing the name of
* the SASL mechanism and an (optional) initial response. It then might use the
* server as follows:</p>
*
* <pre>
*while (!ss.isComplete()) {
* try {
* byte[] challenge = ss.evaluateResponse(response);
* if (ss.isComplete()) {
* status = ldap.sendBindResponse(mechanism, challenge, SUCCESS);
* } else {
* status = ldap.sendBindResponse(mechanism, challenge, SASL_BIND_IN_PROGRESS);
* response = ldap.readBindRequest();
* }
* } catch (SaslException x) {
* status = ldap.sendErrorResponse(x);
* break;
* }
*}
*if (ss.isComplete() && (status == SUCCESS)) {
* String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
* if (qop != null
* && (qop.equalsIgnoreCase("auth-int")
* || qop.equalsIgnoreCase("auth-conf"))) {
* // Use SaslServer.wrap() and SaslServer.unwrap() for future
* // communication with client
* ldap.in = new SecureInputStream(ss, ldap.in);
* ldap.out = new SecureOutputStream(ss, ldap.out);
* }
*}
* </pre>
*
* @see Sasl
* @see SaslServerFactory
*
* @since 1.5
*/
public interface SaslServer
{
/**
* Returns the IANA-registered mechanism name of this SASL server (e.g.
* "CRAM-MD5", "GSSAPI").
*
* @return a non-null string representing the IANA-registered mechanism name.
*/
String getMechanismName();
/**
* Evaluates the response data and generates a challenge. If a response is
* received from the client during the authentication process, this method is
* called to prepare an appropriate next challenge to submit to the client.
* The challenge is <code>null</code> if the authentication has succeeded and
* no more challenge data is to be sent to the client. It is non-null if the
* authentication must be continued by sending a challenge to the client, or
* if the authentication has succeeded but challenge data needs to be
* processed by the client. {@link #isComplete()} should be called after each
* call to <code>evaluateResponse()</code>,to determine if any further
* response is needed from the client.
*
* @param response the non-null (but possibly empty) response sent by the
* client.
* @return the possibly <code>null</code> challenge to send to the client.
* It is <code>null</code> if the authentication has succeeded and there is
* no more challenge data to be sent to the client.
* @throws SaslException if an error occurred while processing the response
* or generating a challenge.
*/
byte[] evaluateResponse(byte[] response) throws SaslException;
/**
* Determines if the authentication exchange has completed. This method is
* typically called after each invocation of {@link #evaluateResponse(byte[])}
* to determine whether the authentication has completed successfully or
* should be continued.
*
* @return <code>true</code> if the authentication exchange has completed;
* <code>false</code> otherwise.
*/
boolean isComplete();
/**
* Reports the authorization ID in effect for the client of this session This
* method can only be called if {@link #isComplete()} returns <code>true</code>.
*
* @return the authorization ID of the client.
* @throws IllegalStateException if this authentication session has not
* completed.
*/
String getAuthorizationID();
/**
* <p>Unwraps a byte array received from the client. This method can be called
* only after the authentication exchange has completed (i.e., when
* {@link #isComplete()} returns <code>true</code>) and only if the
* authentication exchange has negotiated integrity and/or privacy as the
* quality of protection; otherwise, an {@link IllegalStateException} is
* thrown.</p>
*
* <p><code>incoming</code> is the contents of the SASL buffer as defined in
* RFC 2222 without the leading four octet field that represents the length.
* <code>offset</code> and <code>len</code> specify the portion of incoming
* to use.</p>
*
* @param incoming a non-null byte array containing the encoded bytes from
* the client.
* @param offset the starting position at <code>incoming</code> of the bytes
* to use.
* @param len the number of bytes from <code>incoming</code> to use.
* @return a non-null byte array containing the decoded bytes.
* @throws SaslException if <code>incoming</code> cannot be successfully
* unwrapped.
* @throws IllegalStateException if the authentication exchange has not
* completed, or if the negotiated quality of protection has neither
* integrity nor privacy.
*/
byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException;
/**
* <p>Wraps a byte array to be sent to the client. This method can be called
* only after the authentication exchange has completed (i.e., when
* {@link #isComplete()} returns <code>true</code>) and only if the
* authentication exchange has negotiated integrity and/or privacy as the
* quality of protection; otherwise, an {@link IllegalStateException} is
* thrown.</p>
*
* <p>The result of this method will make up the contents of the SASL buffer
* as defined in RFC 2222 without the leading four octet field that
* represents the length. <code>offset</code> and <code>len</code> specify
* the portion of <code>outgoing</code> to use.
*
* @param outgoing a non-null byte array containing the bytes to encode.
* @param offset the starting position at <code>outgoing</code> of the bytes
* to use.
* @param len the number of bytes from <code>outgoing</code> to use.
* @return a non-null byte array containing the encoded bytes.
* @throws SaslException if <code>outgoing</code> cannot be successfully
* wrapped.
* @throws IllegalStateException if the authentication exchange has not
* completed, or if the negotiated quality of protection has neither
* integrity nor privacy.
*/
byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException;
/**
* Retrieves the negotiated property. This method can be called only after
* the authentication exchange has completed (i.e., when
* {@link #isComplete()} returns <code>true</code>); otherwise, an
* {@link IllegalStateException} is thrown.
*
* @return the value of the negotiated property. If <code>null</code>, the
* property was not negotiated or is not applicable to this mechanism.
* @throws IllegalStateException if this authentication exchange has not
* completed.
*/
Object getNegotiatedProperty(String propName);
/**
* Disposes of any system resources or security-sensitive information the
* <code>SaslServer</code> might be using. Invoking this method invalidates
* the <code>SaslServer</code> instance. This method is idempotent.
*
* @throws SaslException if a problem was encountered while disposing of the
* resources.
*/
void dispose() throws SaslException;
}
diff --git a/classpath-0.98/javax/security/sasl/SaslServerFactory.java b/classpath-0.98/javax/security/sasl/SaslServerFactory.java
index 6166349..82b7cdc 100644
--- a/classpath-0.98/javax/security/sasl/SaslServerFactory.java
+++ b/classpath-0.98/javax/security/sasl/SaslServerFactory.java
@@ -1,116 +1,117 @@
/* SaslServerFactory.java
Copyright (C) 2003, 2005, Free Software Foundation, Inc.
+ Modified for Android (C) 2009, 2010 by Alexey Kotlyarov
This file is part of GNU Classpath.
GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnusasl.javax.security.sasl;
import java.util.Map;
import javax.security.auth.callback.CallbackHandler;
/**
* <p>An interface for creating instances of {@link SaslServer}. A class that
* implements this interface must be thread-safe and handle multiple
* simultaneous requests. It must also have a public constructor that accepts
* no arguments.</p>
*
* <p>This interface is not normally accessed directly by a server, which will
* use the {@link Sasl} static methods to create a {@link SaslServer} instance
* instead. However, a particular environment may provide and install a new or
* different <code>SaslServerFactory</code>.</p>
*
* @see SaslServer
* @see Sasl
*
* @since 1.5
*/
public interface SaslServerFactory
{
/**
* Creates a {@link SaslServer} instance using the parameters supplied. It
* returns <code>null</code> if no {@link SaslServer} instance can be created
* using the parameters supplied. Throws {@link SaslException} if it cannot
* create a {@link SaslServer} because of an error.
*
* @param mechanism the non-null IANA-registered name of a SASL mechanism
* (e.g. "GSSAPI", "CRAM-MD5").
* @param protocol the non-null string name of the protocol for which the
* authentication is being performed (e.g. "ldap").
* @param serverName the non-null fully qualified host name of the server to
* authenticate to.
* @param props the possibly null set of properties used to select the SASL
* mechanism and to configure the authentication exchange of the selected
* mechanism. See the {@link Sasl} class for a list of standard properties.
* Other, possibly mechanism-specific, properties can be included. Properties
* not relevant to the selected mechanism are ignored.
* @param cbh the possibly null callback handler to used by the SASL
* mechanisms to get further information from the application/library to
* complete the authentication. For example, a SASL mechanism might require
* the authentication ID, password and realm from the caller. The
* authentication ID is requested by using a
* {@link javax.security.auth.callback.NameCallback}. The password is
* requested by using a {@link javax.security.auth.callback.PasswordCallback}.
* The realm is requested by using a {@link RealmChoiceCallback} if there is
* a list of realms to choose from, and by using a {@link RealmCallback} if
* the realm must be entered.
* @return a possibly null {@link SaslServer} created using the parameters
* supplied. If <code>null</code> is returned, it means that this factory
* cannot produce a {@link SaslServer} using the parameters supplied.
* @throws SaslException if a SaslServer instance cannot be created because
* of an error.
*/
SaslServer createSaslServer(String mechanism, String protocol,
String serverName, Map<String, ?> props,
CallbackHandler cbh)
throws SaslException;
/**
* Returns an array of names of mechanisms that match the specified mechanism
* selection policies.
*
* @param props the possibly <code>null</code> set of properties used to
* specify the security policy of the SASL mechanisms. For example, if props
* contains the {@link Sasl#POLICY_NOPLAINTEXT} property with the value
* <code>"true"</code>, then the factory must not return any SASL mechanisms
* that are susceptible to simple plain passive attacks. See the {@link Sasl}
* class for a complete list of policy properties. Non-policy related
* properties, if present in props, are ignored.
* @return a non-null array containing IANA-registered SASL mechanism names.
*/
String[] getMechanismNames(Map<String, ?> props);
}
|
yui/builder
|
1093ebc7a3e9550d7fe9c30720785c16095ed041
|
Added deprecation message to README
|
diff --git a/README.md b/README.md
index 0c0f9a9..166d7ae 100644
--- a/README.md
+++ b/README.md
@@ -1,269 +1,271 @@
Welcome to YUI Builder
======================
+This repo has been deprecated in favor of [Shifter](http://github.com/yui/shifter).
+
Introduction
------------
YUI uses ANT to create component build files from individual source files.
Each component has its own ANT build file residing in the component's
source folder with an associated properties file used to define build
parameters specific to the component e.g:
yui2/src/autocomplete/build.xml
yui2/src/autocomplete/build.properties
The component build will automate the conversion from component source
to <component>.js, <component>-min.js, <component>-debug.js by:
a) Concatenating individual source files
b) Stripping logger statements
c) Compressing files, using yuicompressor
d) Running jslint on all 3 built files
e) Adding boiler plate module/version registration code
f) Building skin files from <component>-core.css, <component>-skin.css
g) Deploying built JS, CSS and assets to <project>/build
The same component build system is also used for CSS components such as
reset, base, fonts and grids.
The component build does not currently:
a) Check in any code
The developer is responsible for checking modified source code
into the <project>/src directory, and built code into the
<project>/build directory, allowing them to review diffs,
before committing changes.
b) Generate API documentation
Installation
------------
Below is a brief summary as well as a detailed step-by-step guide
for installing the build system, allowing you to build the "src"
component code.
Summary
-------
1) Install ANT 1.7 or above, and add ant to your path
2) Clone the YUI "builder" project from http://github.com/yui/builder/
3) At the command line, cd to the source directory of the component
you wish to build, and execute "ant all" to build, e.g.:
prompt> cd yui2/src/autocomplete
prompt> ant all
Detailed Instructions
---------------------
To use the build system, you'll need to install ANT and obtain
the YUI build infrastructure from github.
These are both one-time install tasks.
Installing Ant
--------------
1) Download and install ANT 1.7 (or above)
http://ant.apache.org/bindownload.cgi
2) Be sure to define an ANT_HOME environment variable to point to
your ANT install root, and add the ANT executable to your
environment's PATH variable.
Installing YUI Build Infrastructure
-----------------------------------
1) Clone the YUI "builder" project from github:
http://github.com/yui/builder/
This project contains the files used by the
YUI ant build process.
2) Out of the box, the build system is designed to work
when cloned to the default "builder" directory, parallel
to the project source directories:
<gitroot>/yui2 ( cloned yui2 project )
<gitroot>/yui3 ( cloned yui2 project )
<gitroot>/builder ( cloned builder project )
Cloning it to the default location will allow you to
build any of the components without having to modify any
component build scripts.
NOTE: YUI Builder is also available for download as a zip from
http://yuilibrary.com/downloads. If downloading from this location
to build yui2 or yui3 source, make sure to unzip the contents into
the directory structure mentioned above, to have the build work out
of the box.
Building An Existing Component
------------------------------
With ANT and the YUI build infrastructure installed, you can now build any
of the components from source, using the build.xml file in the component's
source directory.
The build system allows you to build locally, within the component's
source directory, and also run a full build to update the top level build
directory for a component.
Full Build
----------
To perform a full build for a component, run ant with the "all" target:
e.g:
prompt> cd yui2/src/autocomplete
prompt> ant all
The "all" build target will build the component from its source files AND
deploy the built files, as well as any assets, to the top level build
folder:
<project>/build/<component>
So, for autocomplete, the built files would be copied to:
yui2/build/autocomplete
NOTE: When invoking ant without a file argument, as we do above, it will
use build.xml, if present in the current directory - which is what we want.
LOCAL BUILD
To perform a local build for a component, run ant without a target:
e.g:
prompt> cd yui2/src/autocomplete
prompt> ant
This will run the default target, which is "local".
The "local" build target will build the autocomplete component from its
source files, but will NOT deploy the built files to the top level build
folder.
The locally built files are stored in the temporary directory:
<project>/src/<component>/build_tmp
So, for autocomplete, the built files can be found in the directory below:
yui2/src/autocomplete/build_tmp
Build Output
------------
ANT will output build information to the screen, as it runs through the
build, which can be redirected to a file if required:
prompt> ant all
Buildfile: build.xml
[echo] Starting Build For autocomplete
...
[echo] builddir : ../../../builder/componentbuild
...
...
BUILD SUCCESSFUL
Total time: 7 seconds
prompt>
NOTE: Most components will have warnings which are output during the
"minify" and "lint" steps, which the component developer has evaluated
and determined to have no impact on functionality.
Creating Build Files For A New Component
----------------------------------------
The builder/componentbuild/templates directory has basic build.xml and
build.properties templates for the various component types supported.
For most new components, you should be able to start with the
appropriate template files and simply change the values of the basic
properties defined to suit your component.
If you're creating:
* A YUI 2 Component (either a JS or CSS component), use:
builder/componentbuild/templates/yui2
build.xml
build.properties
* A YUI 3 Component (either a JS or CSS component), use:
builder/componentbuild/templates/yui3
build.xml
build.properties
* A YUI 3 Rollup Component, use:
builder/componentbuild/templates/yui3/rollup
For the rollup component:
build.xml
build.properties
For the sub components:
subcomponentone.xml
subcomponentone.properties
subcomponenttwo.xml
subcomponenttwo.properties
Further Customization
---------------------
If required, you can define custom values for any of the properties
defined in builder/componentbuild/docs/properties.html to customize the
build for your new component, however as mentioned above, for most
components the properties defined in the template files should be
sufficient.
You can also override or extend existing targets, to customize the actual
build process for a component if required. The list of targets and their
role is defined in builder/componentbuild/docs/targets.html.
Log Verbosity
-------------
* `ant all` will give you the default log output, may be a little noisy
* `ant all -v` will give you full log output (really noisy)
* `ant all -q` will give you only the jslint output from your build
JSLint/Hint
-----------
By default, we look for the `node` executable. If found we use a Node.js based
JSLint server to lint the JS files. If it's not installed, we fall back to
Rhino (which can be very slow)
If you install the `jshint` (`npm -g i jshint`), we will use that by default.
To skip using this you can pass `-Djshint.skip=true`:
`ant all -q -Djshint.skip=true`
The default is also to only run jslint/hint on RAW files, skipping min and debug versions.
You can change this by adding `-Dlint.all=true` to your command:
`ant all -q -Dlint.all=true`
|
yui/builder
|
1358f0cfb435fc47f68b79446573d14e4235f53d
|
Reduced some of the coverage noise from componentbuilds. echos now have info, and we don't lint coverage files (for now)
|
diff --git a/componentbuild/shared/targets.xml b/componentbuild/shared/targets.xml
index 6e1d643..7448434 100644
--- a/componentbuild/shared/targets.xml
+++ b/componentbuild/shared/targets.xml
@@ -1,240 +1,235 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiSharedTargets">
<echo level="info">Starting Build For ${component}</echo>
<echo level="verbose">Ant Properties</echo>
<echo level="verbose"> Home : ${ant.home}</echo>
<echo level="verbose"> Ant Version : ${ant.version}</echo>
<echo level="verbose"> Build File : ${ant.file}</echo>
<echo level="verbose">Local Build Properties</echo>
<echo level="verbose"> version : ${yui.version}</echo>
<echo level="verbose"> srcdir : ${srcdir}</echo>
<echo level="verbose"> builddir : ${builddir}</echo>
<echo level="verbose"> component : ${component}</echo>
<echo level="verbose"> component.basefilename : ${component.basefilename}</echo>
<echo level="verbose"> component.basedir : ${component.basedir}</echo>
<echo level="verbose"> component.builddir : ${component.builddir}</echo>
<echo level="verbose">Global Build Properties</echo>
<echo level="verbose"> global.build.base : ${global.build.base}</echo>
<echo level="verbose"> global.build.component : ${global.build.component}</echo>
<echo level="verbose"> global.build.component.assets : ${global.build.component.assets}</echo>
<dirname property="targets.basedir" file="${ant.file.YuiSharedTargets}"/>
<import file="${targets.basedir}/macrolib.xml" description="Macrodef definitions - jslint, yuicompessor, registerversion" />
<target name="all" depends="local, deploy" description="Build and Deploy to Global Build Directory" />
<target name="local" depends="clean, init, build, minify, lint" description="Build and Deploy to Local Build Directory" />
<target name="init">
<tstamp/>
<mkdir dir="${component.builddir}" />
<createdetails />
<antcall target="-lint-server"/>
</target>
<target name="-lint-server" description="Start JSLint Server" unless="lint.skip">
<antcall target="-node">
<param name="src" value="${builddir}/lib/jslint/jslint-node.js"/>
</antcall>
</target>
<target name="-node" description="Start NodeJS Server" unless="node.spawn">
<if>
<not>
<http url="${node.jslint.url}"/>
</not>
<then>
<!-- You can't set failifexecutionfails if spawn is true. Argh. -->
<!-- Check if it's installed first. -->
<exec resultproperty="node.status" executable="node" failonerror="false" failifexecutionfails="false" searchpath="true" resolveexecutable="true">
<arg value="-v"/>
</exec>
<if>
<equals arg1="${node.status}" arg2="0"/>
<then>
<echo level="info">Spawning Node.js app at: ${src}</echo>
<exec executable="node" spawn="true" failonerror="false" searchpath="true" resolveexecutable="true">
<arg value="${src}"/>
</exec>
</then>
<else>
<echo level="info">For faster builds, install Node.js.</echo>
</else>
</if>
<!-- Don't fail if node doesn't exist, fails to start, etc.
We will fallback to the slow Rhino engine later. -->
</then>
</if>
<!-- Don't try to start again. -->
<property name="node.spawn" value="true"/>
</target>
<target name="clean" description="Clean Local Build Directory" unless="clean.skip">
<delete dir="${component.builddir}" />
</target>
<target name="build" />
<target name="build-coverage" unless="coverage.skip">
- <echo>Creating coverage file for: ${component.builddir}/${component.basefilename}.js</echo>
+ <echo level="info">Creating coverage file for: ${component.builddir}/${component.basefilename}.js</echo>
<yuicoverage src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-coverage.js" />
<move file="${component.builddir}/${component.basefilename}-coverage.js" tofile="${component.builddir}/${component.basefilename}-coverage.js.tmp" />
<move file="${component.builddir}/${component.basefilename}-coverage.js.tmp" tofile="${component.builddir}/${component.basefilename}-coverage.js">
<filterchain>
<tokenfilter>
<replacestring from="${component.builddir}" to="/build/${component.basefilename}"/>
</tokenfilter>
</filterchain>
</move>
</target>
<!-- MIN -->
<target name="minify" description="Create component-min.js from component.js" depends="build-coverage">
<yuicompress src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-min.js" args="${yuicompressor.js.args.internal}" />
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<for param="file">
<path>
<fileset dir="${component.builddir}/lang" includes="*.js"/>
</path>
<sequential>
<yuicompress src="@{file}" dest="@{file}" args="${yuicompressor.js.args.internal}" />
</sequential>
</for>
</then>
</if>
</target>
<target name="lint" description="Run jslint over the local build files (default settings)" unless="lint.skip">
<if>
<istrue value="${lint.all}" />
<then>
<!-- Lint all files -->
<jslint>
<jsfiles>
- <fileset dir="${component.builddir}" includes="*.js" />
+ <fileset dir="${component.builddir}" includes="*.js" excludes="*-coverage.js" />
</jsfiles>
</jslint>
</then>
<else>
<!-- Only lint raw files -->
<jslint>
<jsfiles>
- <fileset dir="${component.builddir}" includes="*.js">
- <none>
- <filename name="*-debug.js"/>
- <filename name="*-min.js"/>
- </none>
- </fileset>
+ <fileset dir="${component.builddir}" includes="*.js" excludes="*-coverage.js, *-debug.js, *-min.js" />
</jsfiles>
</jslint>
</else>
</if>
</target>
<!-- DEPLOY -->
<target name="deploy" description="Copy files to global location" depends="deploybuild, deployassets, deployskins, deploylang, deploydocs"></target>
<target name="deploybuild" description="Copy built files to global build location">
<copy todir="${global.build.component}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}" includes="*.js" />
</copy>
</target>
<target name="deployassets" if="component.assets.exist">
<copy todir="${global.build.component.assets}" flatten="${component.assets.flatten}" overwrite="true" verbose="false">
<fileset dir="${component.assets.base}" includes="${component.assets.files}" excludes="skins/, legacy/" />
</copy>
<copy todir="${global.build.component.assets}" flatten="${component.assets.legacy.flatten}" preservelastmodified="true" failonerror="false" verbose="false">
<fileset dir="${component.assets.legacy.base}" includes="${component.assets.legacy.files}" excludes="skins/" />
</copy>
</target>
<target name="deployskins" if="skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Deploying Skin files for @{skin.dir} :: ${skin.name}</echo>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" />
</copy>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.assets.skins.base}/${skin.name}" includes="${component.assets.skins.files}" />
</copy>
<var name="skin.name" unset="true" />
</sequential>
</for>
</target>
<target name="deploylang" description="Copy language bundles to global build location">
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<copy todir="${global.build.component}/lang" overwrite="true" failonerror="false">
<fileset dir="${component.builddir}/lang" includes="*.js" />
</copy>
</then>
</if>
</target>
<target name="deploydocs" description="Copy doc files to global doc locations">
<!-- TODO -->
</target>
<target name="-prepend" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true">
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true" append="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<move file="${workingdir}/${component.basefilename}.js.tmp" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-append" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
</target>
<target name="-prependdebug" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}-debug.js.tmp" fixlastline="true" >
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
<move file="${workingdir}/${component.basefilename}-debug.js.tmp" tofile="${component.builddir}/${component.basefilename}-debug.js" />
</target>
<target name="-appenddebug" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}-debug.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
</concat>
</target>
</project>
|
yui/builder
|
85679053f83b93500df3b38cf37c847a09be583a
|
Added more global ignores to jslint config, for coverage files (to reduce noise when doing an ant -Dlint.all=true)
|
diff --git a/componentbuild/lib/jslint/jslint-console.js b/componentbuild/lib/jslint/jslint-console.js
index 5edb58f..aaf97eb 100644
--- a/componentbuild/lib/jslint/jslint-console.js
+++ b/componentbuild/lib/jslint/jslint-console.js
@@ -1,72 +1,75 @@
/**
* Javascript Shell Script to Load and JSLint js files through Rhino Javascript Shell
* The jslint source file is expected as the first argument, followed by the list of JS files to JSLint
*
* e.g.
* java -j js.jar /tools/fulljslint.js testFile1.js testFile2.js testFile3.js
**/
var jslintsrc = arguments.splice(0,1);
var scripts = arguments;
load(jslintsrc);
(function(){ // Just to keep stuff seperate from JSLINT code
var OPTS = {
browser : true,
//laxLineEnd : true,
undef: true,
newcap: false,
predef:["YUI", "window", "YUI_config", "YAHOO", "YAHOO_config", "Event",
+ "_yuitest_coverline",
+ "_yuitest_coverage",
+ "_yuitest_coverfunc",
"opera", "exports", "document", "navigator", "console", "self"]
};
function test(jsFile) {
print("Running JSLint on : " + jsFile);
var js = readFile(jsFile);
var success = JSLINT(js, OPTS);
if (success) {
print("- OK");
} else {
print(" \n");
for (var i=0; i < JSLINT.errors.length; ++i) {
var e = JSLINT.errors[i];
if (e) {
print("\t" + e.line + ", " + e.character + ": " + e.reason + "\n\t" + clean(e.evidence) + "\n");
}
}
print(" \n");
// Last item is null if JSLint hit a fatal error
if (JSLINT.errors && JSLINT.errors[JSLINT.errors.length-1] === null) {
throw new Error("Fatal JSLint Exception. Stopped lint");
}
}
}
function clean(str) {
var trimmed = "";
if (str) {
if(str.length <= 500) {
trimmed = str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
} else {
trimmed = "[Code Evidence Omitted: Greater than 500 chars]";
}
}
return trimmed;
}
function jslint(aScripts) {
for (var i = 0; i < aScripts.length; ++i) {
test(aScripts[i]);
}
};
jslint(scripts);
})();
diff --git a/componentbuild/lib/jslint/jslint-node.js b/componentbuild/lib/jslint/jslint-node.js
index bc7646f..a37b5bd 100644
--- a/componentbuild/lib/jslint/jslint-node.js
+++ b/componentbuild/lib/jslint/jslint-node.js
@@ -1,127 +1,130 @@
/**
* Javascript Shell Script to Load and JSLint js files through Rhino Javascript Shell
* The jslint source file is expected as the first argument, followed by the list of JS files to JSLint
*
* e.g.
* java -j js.jar /tools/fulljslint.js testFile1.js testFile2.js testFile3.js
**/
JSLINT = require("./fulljslint").JSLINT;
(function(){ // Just to keep stuff seperate from JSLINT code
var PORT = parseInt(process.argv[2]) || 8081;
var OPTS = {
browser : true,
//laxLineEnd : true,
undef: true,
newcap: false,
predef:["YUI", "window", "YUI_config", "YAHOO", "YAHOO_config", "Event",
"opera", "exports", "document", "navigator", "console", "self", "require",
+ "_yuitest_coverline",
+ "_yuitest_coverfunc",
+ "_yuitest_coverage",
"module", "process", "__dirname", "__filename"]
};
function test(js, file) {
var body = "", code = 200;
var success = JSLINT(js, OPTS);
if (success) {
return {
"content": '\t[JSLINT] [OK] ' + file,
code: code
};
} else {
if (JSLINT.errors.length) {
body += '[JSLINT] ' + file + '\n';
body += '----------------------------------------------------------\n';
for (var i=0; i < JSLINT.errors.length; ++i) {
var e = JSLINT.errors[i];
if (e) {
body += ("\t" + e.line + ", " + e.character + ": " + e.reason + "\n\t" + clean(e.evidence) + "\n");
}
}
body += '----------------------------------------------------------\n';
}
// Last item is null if JSLint hit a fatal error
if (JSLINT.errors && JSLINT.errors[JSLINT.errors.length-1] === null) {
code = 500;
}
return {
"content" : body,
"code" : code
};
}
}
function clean(str) {
var trimmed = "";
if (str) {
if(str.length <= 500) {
trimmed = str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
} else {
trimmed = "[Code Evidence Omitted: Greater than 500 chars]";
}
}
return trimmed;
}
var qs = require("querystring");
var fs = require("fs");
var EventEmitter = require("events").EventEmitter;
var ticket = 0;
require("http").createServer(function (req, res) {
var data = "";
req.addListener("data", function (chunk) {
data += chunk;
});
var proc = new EventEmitter();
proc.addListener("end", function (code, body, die) {
res.writeHead(code, {"Content-type" : "text/plain"});
res.end(body);
if (die) process.exit(0);
});
req.addListener("end", function () {
ticket++;
var code = 200, body;
var die = "/kill" === req.url;
if (die) body = "Goodbye.";
else if (req.method === "POST") {
var query = qs.parse(data);
var files = query["files"].split("' '");
var failOnError = query["failonerror"] == "true";
var results = [];
files.forEach(function (file) {
fs.readFile(file, function (err, data) {
var diagnosis = test(data.toString("utf8"), file);
results.push(diagnosis.content);
code = (
failOnError &&
diagnosis.code !== 200
) ? diagnosis.code : code;
if (results.length == files.length) proc.emit("end", code, results.join("\n"));
});
});
} else {
body = "Ready.";
}
if (body) proc.emit("end", code, body, die);
});
}).listen(PORT, "127.0.0.1");
console.log("Server started on port " + PORT);
(function () {
var reap;
setInterval(function () {
if (reap == ticket) process.exit(0);
reap = ticket;
}, 10000);
})();
})();
|
yui/builder
|
e35347b2d9400d2a1ff1ef3e86f6f0a7d81ebea8
|
Remove file paths from -coverage files after they are processed
|
diff --git a/componentbuild/shared/targets.xml b/componentbuild/shared/targets.xml
index 0ec3de7..6e1d643 100644
--- a/componentbuild/shared/targets.xml
+++ b/componentbuild/shared/targets.xml
@@ -1,231 +1,240 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiSharedTargets">
<echo level="info">Starting Build For ${component}</echo>
<echo level="verbose">Ant Properties</echo>
<echo level="verbose"> Home : ${ant.home}</echo>
<echo level="verbose"> Ant Version : ${ant.version}</echo>
<echo level="verbose"> Build File : ${ant.file}</echo>
<echo level="verbose">Local Build Properties</echo>
<echo level="verbose"> version : ${yui.version}</echo>
<echo level="verbose"> srcdir : ${srcdir}</echo>
<echo level="verbose"> builddir : ${builddir}</echo>
<echo level="verbose"> component : ${component}</echo>
<echo level="verbose"> component.basefilename : ${component.basefilename}</echo>
<echo level="verbose"> component.basedir : ${component.basedir}</echo>
<echo level="verbose"> component.builddir : ${component.builddir}</echo>
<echo level="verbose">Global Build Properties</echo>
<echo level="verbose"> global.build.base : ${global.build.base}</echo>
<echo level="verbose"> global.build.component : ${global.build.component}</echo>
<echo level="verbose"> global.build.component.assets : ${global.build.component.assets}</echo>
<dirname property="targets.basedir" file="${ant.file.YuiSharedTargets}"/>
<import file="${targets.basedir}/macrolib.xml" description="Macrodef definitions - jslint, yuicompessor, registerversion" />
<target name="all" depends="local, deploy" description="Build and Deploy to Global Build Directory" />
<target name="local" depends="clean, init, build, minify, lint" description="Build and Deploy to Local Build Directory" />
<target name="init">
<tstamp/>
<mkdir dir="${component.builddir}" />
<createdetails />
<antcall target="-lint-server"/>
</target>
<target name="-lint-server" description="Start JSLint Server" unless="lint.skip">
<antcall target="-node">
<param name="src" value="${builddir}/lib/jslint/jslint-node.js"/>
</antcall>
</target>
<target name="-node" description="Start NodeJS Server" unless="node.spawn">
<if>
<not>
<http url="${node.jslint.url}"/>
</not>
<then>
<!-- You can't set failifexecutionfails if spawn is true. Argh. -->
<!-- Check if it's installed first. -->
<exec resultproperty="node.status" executable="node" failonerror="false" failifexecutionfails="false" searchpath="true" resolveexecutable="true">
<arg value="-v"/>
</exec>
<if>
<equals arg1="${node.status}" arg2="0"/>
<then>
<echo level="info">Spawning Node.js app at: ${src}</echo>
<exec executable="node" spawn="true" failonerror="false" searchpath="true" resolveexecutable="true">
<arg value="${src}"/>
</exec>
</then>
<else>
<echo level="info">For faster builds, install Node.js.</echo>
</else>
</if>
<!-- Don't fail if node doesn't exist, fails to start, etc.
We will fallback to the slow Rhino engine later. -->
</then>
</if>
<!-- Don't try to start again. -->
<property name="node.spawn" value="true"/>
</target>
<target name="clean" description="Clean Local Build Directory" unless="clean.skip">
<delete dir="${component.builddir}" />
</target>
<target name="build" />
<target name="build-coverage" unless="coverage.skip">
<echo>Creating coverage file for: ${component.builddir}/${component.basefilename}.js</echo>
<yuicoverage src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-coverage.js" />
+ <move file="${component.builddir}/${component.basefilename}-coverage.js" tofile="${component.builddir}/${component.basefilename}-coverage.js.tmp" />
+
+ <move file="${component.builddir}/${component.basefilename}-coverage.js.tmp" tofile="${component.builddir}/${component.basefilename}-coverage.js">
+ <filterchain>
+ <tokenfilter>
+ <replacestring from="${component.builddir}" to="/build/${component.basefilename}"/>
+ </tokenfilter>
+ </filterchain>
+ </move>
</target>
<!-- MIN -->
<target name="minify" description="Create component-min.js from component.js" depends="build-coverage">
<yuicompress src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-min.js" args="${yuicompressor.js.args.internal}" />
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<for param="file">
<path>
<fileset dir="${component.builddir}/lang" includes="*.js"/>
</path>
<sequential>
<yuicompress src="@{file}" dest="@{file}" args="${yuicompressor.js.args.internal}" />
</sequential>
</for>
</then>
</if>
</target>
<target name="lint" description="Run jslint over the local build files (default settings)" unless="lint.skip">
<if>
<istrue value="${lint.all}" />
<then>
<!-- Lint all files -->
<jslint>
<jsfiles>
<fileset dir="${component.builddir}" includes="*.js" />
</jsfiles>
</jslint>
</then>
<else>
<!-- Only lint raw files -->
<jslint>
<jsfiles>
<fileset dir="${component.builddir}" includes="*.js">
<none>
<filename name="*-debug.js"/>
<filename name="*-min.js"/>
</none>
</fileset>
</jsfiles>
</jslint>
</else>
</if>
</target>
<!-- DEPLOY -->
<target name="deploy" description="Copy files to global location" depends="deploybuild, deployassets, deployskins, deploylang, deploydocs"></target>
<target name="deploybuild" description="Copy built files to global build location">
<copy todir="${global.build.component}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}" includes="*.js" />
</copy>
</target>
<target name="deployassets" if="component.assets.exist">
<copy todir="${global.build.component.assets}" flatten="${component.assets.flatten}" overwrite="true" verbose="false">
<fileset dir="${component.assets.base}" includes="${component.assets.files}" excludes="skins/, legacy/" />
</copy>
<copy todir="${global.build.component.assets}" flatten="${component.assets.legacy.flatten}" preservelastmodified="true" failonerror="false" verbose="false">
<fileset dir="${component.assets.legacy.base}" includes="${component.assets.legacy.files}" excludes="skins/" />
</copy>
</target>
<target name="deployskins" if="skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Deploying Skin files for @{skin.dir} :: ${skin.name}</echo>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" />
</copy>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.assets.skins.base}/${skin.name}" includes="${component.assets.skins.files}" />
</copy>
<var name="skin.name" unset="true" />
</sequential>
</for>
</target>
<target name="deploylang" description="Copy language bundles to global build location">
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<copy todir="${global.build.component}/lang" overwrite="true" failonerror="false">
<fileset dir="${component.builddir}/lang" includes="*.js" />
</copy>
</then>
</if>
</target>
<target name="deploydocs" description="Copy doc files to global doc locations">
<!-- TODO -->
</target>
<target name="-prepend" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true">
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true" append="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<move file="${workingdir}/${component.basefilename}.js.tmp" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-append" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
</target>
<target name="-prependdebug" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}-debug.js.tmp" fixlastline="true" >
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
<move file="${workingdir}/${component.basefilename}-debug.js.tmp" tofile="${component.builddir}/${component.basefilename}-debug.js" />
</target>
<target name="-appenddebug" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}-debug.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
</concat>
</target>
</project>
|
yui/builder
|
c786859eb9a888182b1a79f6010edd31e3877fde
|
Moving tasks around
|
diff --git a/componentbuild/3.x/module.xml b/componentbuild/3.x/module.xml
index 3492ba1..525d566 100644
--- a/componentbuild/3.x/module.xml
+++ b/componentbuild/3.x/module.xml
@@ -1,177 +1,172 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiModuleTargets">
<dirname property="module.basedir" file="${ant.file.YuiModuleTargets}"/>
<import file="${module.basedir}/../shared/targets.xml" description="Targets common to Rollup/Module" />
- <target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs, build-coverage" />
+ <target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs" />
<target name="buildskins" depends="-buildskins, -rollupcss" />
<target name="buildlangs" depends="-buildlangs, -rolluplangs" />
<!-- CORE -->
<target name="buildcore" depends="builddebug, -createcore, -loggerregex" description="Create component.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}.js" eol="${buildfiles.eol}" />
</target>
<target name="-createcore">
<copy file="${component.builddir}/${component.basefilename}-debug.js" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-loggerregex" description="Replace logger statements" unless="component.logger.regex.skip">
<echo level="verbose">Replacing Logger Statements in ${component.builddir}/${component.basefilename}.js</echo>
<replaceregexp file="${component.builddir}/${component.basefilename}.js"
byline="${component.logger.regex.byline}"
match="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</target>
- <target name="build-coverage" unless="coverage.skip">
- <echo>Creating coverage file for: ${component.builddir}/${component.basefilename}.js</echo>
- <yuicoverage src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-coverage.js" />
- </target>
-
<!-- DEBUG -->
<target name="builddebug" depends="-concatdebug, -registerdebug, -prependdebug, -appenddebug" description="Create component-debug.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}-debug.js" eol="${buildfiles.eol}" />
</target>
<target name="-concatdebug">
<concatsource destfile="${component.builddir}/${component.basefilename}-debug.js" sourcedir="${component.jsfiles.base}" sourcefiles="${component.jsfiles}" />
</target>
<target name="-registerdebug" unless="register.skip">
<addmodule module="${component.module}" file="${component.builddir}/${component.basefilename}-debug.js" details="${component.details.hash}" />
</target>
<target name="-rollupjs" if="rollup">
<if>
<isset property="rollup.sub"/>
<then>
<echo level="verbose">Module: Build a rollup of a rollup; moving rollup.sub properties into rollup properties.</echo>
<var name="rollup.builddir" unset="true"/>
<var name="rollup.component" unset="true"/>
<var name="rollup.component.basefilename" unset="true"/>
<propertycopy name="rollup.builddir" from="rollup.sub.builddir"/>
<propertycopy name="rollup.component" from="rollup.sub.component"/>
<propertycopy name="rollup.component.basefilename" from="rollup.sub.component.basefilename"/>
</then>
</if>
<echo level="verbose">Module: Rolling up ${component.basefilename}-debug.js into ${rollup.component.basefilename}-debug.js</echo>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}-debug.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
</target>
<!-- SKINS -->
<target name="-buildskins" depends="-concatskins" description="Create skin rollup in local component build directory" if="component.skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Fixing CRLF for Skin files for @{skin.dir} :: ${skin.name}</echo>
<fixcrlf srcdir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" eol="${buildfiles.eol}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--fixcrlf srcdir="${component.builddir}/assets/skins/sam" includes="${component}.css" eol="${buildfiles.eol}" /-->
</target>
<target name="-buildlangs" description="Create language packs in the local component build directory" if="component.langs.exist">
<mkdir dir="${component.builddir}/lang" />
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<addlang dir="${component.lang.base}" module="${component}" lang="@{lang}" dest="${component.builddir}/lang" />
</sequential>
</for>
<addlang dir="${component.lang.base}" module="${component}" lang="" dest="${component.builddir}/lang/" />
</target>
<target name="-rolluplangs" if="rolluplangs">
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<concat destfile="${rollup.builddir}/lang/${rollup.component}_@{lang}.js" append="true" fixlastline="true">
<fileset dir="${component.builddir}/lang" includes="*_@{lang}.js" />
</concat>
</sequential>
</for>
<concat destfile="${rollup.builddir}/lang/${rollup.component}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}/lang" files="${component}.js" />
</concat>
</target>
<target name="-concatskins" if="component.skins.exist">
<echo level="verbose">Concating Skins</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concatsource destfile="${component.builddir}/assets/skins/${skin.name}/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/${skin.name}/${component}-skin.css" />
<!-- Stamp Skin CSS -->
<stampcss file="${component.builddir}/assets/skins/${skin.name}/${component}.css" module="skin-${skin.name}-${component}" />
<yuicompress type="css" src="${component.builddir}/assets/skins/${skin.name}/${component}.css" dest="${component.builddir}/assets/skins/${skin.name}/${component}.css" args="${yuicompressor.css.args.internal}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concatsource destfile="${component.builddir}/assets/skins/sam/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/sam/${component}-skin.css" />
<yuicompress type="css" src="${component.builddir}/assets/skins/sam/${component}.css" dest="${component.builddir}/assets/skins/sam/${component}.css" args="${yuicompressor.css.args.internal}" /-->
</target>
<target name="-rollupcss" if="rollupskins">
<echo level="verbose">Rolling up ${component}.css into ${rollup.component}.css</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concat destfile="${rollup.builddir}/assets/skins/${skin.name}/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/${skin.name}" files="${component}.css" />
</concat>
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concat destfile="${rollup.builddir}/assets/skins/sam/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/sam" files="${component}.css" />
</concat-->
</target>
<!-- Tests -->
<target name="tests" depends="-lint-server">
<echo level="info">Generating test module for ${component}</echo>
<echo level="info"> Test module: ${tests.component}</echo>
<echo level="info"> Test module source directory: ${tests.srcdir}</echo>
<echo level="info"> Test module source files: ${tests.jsfiles}</echo>
<echo level="info"> Test module output directory: ${tests.builddir}</echo>
<echo level="info"> Test module file: ${tests.builddir}/${tests.component}.js</echo>
<echo level="info"> </echo>
<available file="${tests.srcdir}" type="dir" property="tests.srcdir.exists"/>
<var name="buildfile" value="${tests.builddir}/${tests.component}.js"/>
<arrayliteral from="tests.requires" to="tests.details.requires" key="requires"/>
<concatsource destfile="${buildfile}" sourcedir="${tests.srcdir}" sourcefiles="${tests.jsfiles}"/>
<addmodule file="${buildfile}" module="${tests.component}" details="{${tests.details.requires}}"/>
<jslint>
<jsfiles>
<fileset file="${buildfile}"/>
</jsfiles>
</jslint>
<echo level="info">Test module ${tests.component} created</echo>
</target>
</project>
diff --git a/componentbuild/shared/targets.xml b/componentbuild/shared/targets.xml
index fc0f03a..0ec3de7 100644
--- a/componentbuild/shared/targets.xml
+++ b/componentbuild/shared/targets.xml
@@ -1,226 +1,231 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiSharedTargets">
<echo level="info">Starting Build For ${component}</echo>
<echo level="verbose">Ant Properties</echo>
<echo level="verbose"> Home : ${ant.home}</echo>
<echo level="verbose"> Ant Version : ${ant.version}</echo>
<echo level="verbose"> Build File : ${ant.file}</echo>
<echo level="verbose">Local Build Properties</echo>
<echo level="verbose"> version : ${yui.version}</echo>
<echo level="verbose"> srcdir : ${srcdir}</echo>
<echo level="verbose"> builddir : ${builddir}</echo>
<echo level="verbose"> component : ${component}</echo>
<echo level="verbose"> component.basefilename : ${component.basefilename}</echo>
<echo level="verbose"> component.basedir : ${component.basedir}</echo>
<echo level="verbose"> component.builddir : ${component.builddir}</echo>
<echo level="verbose">Global Build Properties</echo>
<echo level="verbose"> global.build.base : ${global.build.base}</echo>
<echo level="verbose"> global.build.component : ${global.build.component}</echo>
<echo level="verbose"> global.build.component.assets : ${global.build.component.assets}</echo>
<dirname property="targets.basedir" file="${ant.file.YuiSharedTargets}"/>
<import file="${targets.basedir}/macrolib.xml" description="Macrodef definitions - jslint, yuicompessor, registerversion" />
<target name="all" depends="local, deploy" description="Build and Deploy to Global Build Directory" />
<target name="local" depends="clean, init, build, minify, lint" description="Build and Deploy to Local Build Directory" />
<target name="init">
<tstamp/>
<mkdir dir="${component.builddir}" />
<createdetails />
<antcall target="-lint-server"/>
</target>
<target name="-lint-server" description="Start JSLint Server" unless="lint.skip">
<antcall target="-node">
<param name="src" value="${builddir}/lib/jslint/jslint-node.js"/>
</antcall>
</target>
<target name="-node" description="Start NodeJS Server" unless="node.spawn">
<if>
<not>
<http url="${node.jslint.url}"/>
</not>
<then>
<!-- You can't set failifexecutionfails if spawn is true. Argh. -->
<!-- Check if it's installed first. -->
<exec resultproperty="node.status" executable="node" failonerror="false" failifexecutionfails="false" searchpath="true" resolveexecutable="true">
<arg value="-v"/>
</exec>
<if>
<equals arg1="${node.status}" arg2="0"/>
<then>
<echo level="info">Spawning Node.js app at: ${src}</echo>
<exec executable="node" spawn="true" failonerror="false" searchpath="true" resolveexecutable="true">
<arg value="${src}"/>
</exec>
</then>
<else>
<echo level="info">For faster builds, install Node.js.</echo>
</else>
</if>
<!-- Don't fail if node doesn't exist, fails to start, etc.
We will fallback to the slow Rhino engine later. -->
</then>
</if>
<!-- Don't try to start again. -->
<property name="node.spawn" value="true"/>
</target>
<target name="clean" description="Clean Local Build Directory" unless="clean.skip">
<delete dir="${component.builddir}" />
</target>
<target name="build" />
+ <target name="build-coverage" unless="coverage.skip">
+ <echo>Creating coverage file for: ${component.builddir}/${component.basefilename}.js</echo>
+ <yuicoverage src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-coverage.js" />
+ </target>
+
<!-- MIN -->
- <target name="minify" description="Create component-min.js from component.js">
+ <target name="minify" description="Create component-min.js from component.js" depends="build-coverage">
<yuicompress src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-min.js" args="${yuicompressor.js.args.internal}" />
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<for param="file">
<path>
<fileset dir="${component.builddir}/lang" includes="*.js"/>
</path>
<sequential>
<yuicompress src="@{file}" dest="@{file}" args="${yuicompressor.js.args.internal}" />
</sequential>
</for>
</then>
</if>
</target>
<target name="lint" description="Run jslint over the local build files (default settings)" unless="lint.skip">
<if>
<istrue value="${lint.all}" />
<then>
<!-- Lint all files -->
<jslint>
<jsfiles>
<fileset dir="${component.builddir}" includes="*.js" />
</jsfiles>
</jslint>
</then>
<else>
<!-- Only lint raw files -->
<jslint>
<jsfiles>
<fileset dir="${component.builddir}" includes="*.js">
<none>
<filename name="*-debug.js"/>
<filename name="*-min.js"/>
</none>
</fileset>
</jsfiles>
</jslint>
</else>
</if>
</target>
<!-- DEPLOY -->
<target name="deploy" description="Copy files to global location" depends="deploybuild, deployassets, deployskins, deploylang, deploydocs"></target>
<target name="deploybuild" description="Copy built files to global build location">
<copy todir="${global.build.component}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}" includes="*.js" />
</copy>
</target>
<target name="deployassets" if="component.assets.exist">
<copy todir="${global.build.component.assets}" flatten="${component.assets.flatten}" overwrite="true" verbose="false">
<fileset dir="${component.assets.base}" includes="${component.assets.files}" excludes="skins/, legacy/" />
</copy>
<copy todir="${global.build.component.assets}" flatten="${component.assets.legacy.flatten}" preservelastmodified="true" failonerror="false" verbose="false">
<fileset dir="${component.assets.legacy.base}" includes="${component.assets.legacy.files}" excludes="skins/" />
</copy>
</target>
<target name="deployskins" if="skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Deploying Skin files for @{skin.dir} :: ${skin.name}</echo>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" />
</copy>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.assets.skins.base}/${skin.name}" includes="${component.assets.skins.files}" />
</copy>
<var name="skin.name" unset="true" />
</sequential>
</for>
</target>
<target name="deploylang" description="Copy language bundles to global build location">
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<copy todir="${global.build.component}/lang" overwrite="true" failonerror="false">
<fileset dir="${component.builddir}/lang" includes="*.js" />
</copy>
</then>
</if>
</target>
<target name="deploydocs" description="Copy doc files to global doc locations">
<!-- TODO -->
</target>
<target name="-prepend" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true">
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true" append="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<move file="${workingdir}/${component.basefilename}.js.tmp" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-append" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
</target>
<target name="-prependdebug" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}-debug.js.tmp" fixlastline="true" >
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
<move file="${workingdir}/${component.basefilename}-debug.js.tmp" tofile="${component.builddir}/${component.basefilename}-debug.js" />
</target>
<target name="-appenddebug" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}-debug.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
</concat>
</target>
</project>
|
yui/builder
|
9f94e2caef0827bd05714ec0ec84462d9c19a423
|
Added a coverage target to instrument modules with yuitest code coverage
|
diff --git a/componentbuild/3.x/module.xml b/componentbuild/3.x/module.xml
index 525d566..3492ba1 100644
--- a/componentbuild/3.x/module.xml
+++ b/componentbuild/3.x/module.xml
@@ -1,172 +1,177 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiModuleTargets">
<dirname property="module.basedir" file="${ant.file.YuiModuleTargets}"/>
<import file="${module.basedir}/../shared/targets.xml" description="Targets common to Rollup/Module" />
- <target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs" />
+ <target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs, build-coverage" />
<target name="buildskins" depends="-buildskins, -rollupcss" />
<target name="buildlangs" depends="-buildlangs, -rolluplangs" />
<!-- CORE -->
<target name="buildcore" depends="builddebug, -createcore, -loggerregex" description="Create component.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}.js" eol="${buildfiles.eol}" />
</target>
<target name="-createcore">
<copy file="${component.builddir}/${component.basefilename}-debug.js" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-loggerregex" description="Replace logger statements" unless="component.logger.regex.skip">
<echo level="verbose">Replacing Logger Statements in ${component.builddir}/${component.basefilename}.js</echo>
<replaceregexp file="${component.builddir}/${component.basefilename}.js"
byline="${component.logger.regex.byline}"
match="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</target>
+ <target name="build-coverage" unless="coverage.skip">
+ <echo>Creating coverage file for: ${component.builddir}/${component.basefilename}.js</echo>
+ <yuicoverage src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-coverage.js" />
+ </target>
+
<!-- DEBUG -->
<target name="builddebug" depends="-concatdebug, -registerdebug, -prependdebug, -appenddebug" description="Create component-debug.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}-debug.js" eol="${buildfiles.eol}" />
</target>
<target name="-concatdebug">
<concatsource destfile="${component.builddir}/${component.basefilename}-debug.js" sourcedir="${component.jsfiles.base}" sourcefiles="${component.jsfiles}" />
</target>
<target name="-registerdebug" unless="register.skip">
<addmodule module="${component.module}" file="${component.builddir}/${component.basefilename}-debug.js" details="${component.details.hash}" />
</target>
<target name="-rollupjs" if="rollup">
<if>
<isset property="rollup.sub"/>
<then>
<echo level="verbose">Module: Build a rollup of a rollup; moving rollup.sub properties into rollup properties.</echo>
<var name="rollup.builddir" unset="true"/>
<var name="rollup.component" unset="true"/>
<var name="rollup.component.basefilename" unset="true"/>
<propertycopy name="rollup.builddir" from="rollup.sub.builddir"/>
<propertycopy name="rollup.component" from="rollup.sub.component"/>
<propertycopy name="rollup.component.basefilename" from="rollup.sub.component.basefilename"/>
</then>
</if>
<echo level="verbose">Module: Rolling up ${component.basefilename}-debug.js into ${rollup.component.basefilename}-debug.js</echo>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}-debug.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
</target>
<!-- SKINS -->
<target name="-buildskins" depends="-concatskins" description="Create skin rollup in local component build directory" if="component.skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Fixing CRLF for Skin files for @{skin.dir} :: ${skin.name}</echo>
<fixcrlf srcdir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" eol="${buildfiles.eol}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--fixcrlf srcdir="${component.builddir}/assets/skins/sam" includes="${component}.css" eol="${buildfiles.eol}" /-->
</target>
<target name="-buildlangs" description="Create language packs in the local component build directory" if="component.langs.exist">
<mkdir dir="${component.builddir}/lang" />
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<addlang dir="${component.lang.base}" module="${component}" lang="@{lang}" dest="${component.builddir}/lang" />
</sequential>
</for>
<addlang dir="${component.lang.base}" module="${component}" lang="" dest="${component.builddir}/lang/" />
</target>
<target name="-rolluplangs" if="rolluplangs">
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<concat destfile="${rollup.builddir}/lang/${rollup.component}_@{lang}.js" append="true" fixlastline="true">
<fileset dir="${component.builddir}/lang" includes="*_@{lang}.js" />
</concat>
</sequential>
</for>
<concat destfile="${rollup.builddir}/lang/${rollup.component}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}/lang" files="${component}.js" />
</concat>
</target>
<target name="-concatskins" if="component.skins.exist">
<echo level="verbose">Concating Skins</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concatsource destfile="${component.builddir}/assets/skins/${skin.name}/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/${skin.name}/${component}-skin.css" />
<!-- Stamp Skin CSS -->
<stampcss file="${component.builddir}/assets/skins/${skin.name}/${component}.css" module="skin-${skin.name}-${component}" />
<yuicompress type="css" src="${component.builddir}/assets/skins/${skin.name}/${component}.css" dest="${component.builddir}/assets/skins/${skin.name}/${component}.css" args="${yuicompressor.css.args.internal}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concatsource destfile="${component.builddir}/assets/skins/sam/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/sam/${component}-skin.css" />
<yuicompress type="css" src="${component.builddir}/assets/skins/sam/${component}.css" dest="${component.builddir}/assets/skins/sam/${component}.css" args="${yuicompressor.css.args.internal}" /-->
</target>
<target name="-rollupcss" if="rollupskins">
<echo level="verbose">Rolling up ${component}.css into ${rollup.component}.css</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="verbose">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concat destfile="${rollup.builddir}/assets/skins/${skin.name}/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/${skin.name}" files="${component}.css" />
</concat>
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concat destfile="${rollup.builddir}/assets/skins/sam/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/sam" files="${component}.css" />
</concat-->
</target>
<!-- Tests -->
<target name="tests" depends="-lint-server">
<echo level="info">Generating test module for ${component}</echo>
<echo level="info"> Test module: ${tests.component}</echo>
<echo level="info"> Test module source directory: ${tests.srcdir}</echo>
<echo level="info"> Test module source files: ${tests.jsfiles}</echo>
<echo level="info"> Test module output directory: ${tests.builddir}</echo>
<echo level="info"> Test module file: ${tests.builddir}/${tests.component}.js</echo>
<echo level="info"> </echo>
<available file="${tests.srcdir}" type="dir" property="tests.srcdir.exists"/>
<var name="buildfile" value="${tests.builddir}/${tests.component}.js"/>
<arrayliteral from="tests.requires" to="tests.details.requires" key="requires"/>
<concatsource destfile="${buildfile}" sourcedir="${tests.srcdir}" sourcefiles="${tests.jsfiles}"/>
<addmodule file="${buildfile}" module="${tests.component}" details="{${tests.details.requires}}"/>
<jslint>
<jsfiles>
<fileset file="${buildfile}"/>
</jsfiles>
</jslint>
<echo level="info">Test module ${tests.component} created</echo>
</target>
</project>
diff --git a/componentbuild/lib/yuitest-coverage/yuitest-coverage.jar b/componentbuild/lib/yuitest-coverage/yuitest-coverage.jar
new file mode 100644
index 0000000..453066f
Binary files /dev/null and b/componentbuild/lib/yuitest-coverage/yuitest-coverage.jar differ
diff --git a/componentbuild/shared/macrolib.xml b/componentbuild/shared/macrolib.xml
index 65870d4..58ac6df 100644
--- a/componentbuild/shared/macrolib.xml
+++ b/componentbuild/shared/macrolib.xml
@@ -1,445 +1,459 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiMacroLib">
<macrodef name="arrayliteral">
<attribute name="from" />
<attribute name="to" />
<attribute name="key" />
<sequential>
<if>
<and>
<isset property="@{from}" />
<length string="${@{from}}" when="ne" length="0" />
</and>
<then>
<propertyregex property="array"
override="true"
input="${@{from}}"
casesensitive="false"
regexp="([^\,\s]+)"
replace="'\1'"
/>
<property name="@{to}" value="@{key}:[${array}]" />
</then>
</if>
</sequential>
</macrodef>
<macrodef name="createdetails">
<sequential>
<arrayliteral from="component.use" to="component.details.use" key="use" />
<arrayliteral from="component.supersedes" to="component.details.supersedes" key="supersedes" />
<arrayliteral from="component.requires" to="component.details.requires" key="requires" />
<arrayliteral from="component.optional" to="component.details.optional" key="optional" />
<arrayliteral from="component.after" to="component.details.after" key="after" />
<arrayliteral from="component.lang" to="component.details.lang" key="lang" />
<if>
<isset property="component.skinnable" />
<then>
<property name="component.details.skinnable" value="skinnable:${component.skinnable}" />
</then>
</if>
<propertyselector property="details.list"
delimiter=","
match="component\.details.([^\.]*)"
select="\1"
casesensitive="false" />
<var name="details" value="" />
<if>
<isset property="details.list" />
<then>
<for list="${details.list}" param="val">
<sequential>
<var name="details" value="${component.details.@{val}}, ${details}" />
</sequential>
</for>
<propertyregex property="component.details.hash"
input="{${details}}"
regexp="(\,\s*?\})"
replace="}"
casesensitive="false" />
</then>
<else>
<property name="component.details.hash" value="" />
</else>
</if>
</sequential>
</macrodef>
<if>
<!-- The yui2 builder-integration script embeds macrolib.xml
by itself for other macros, which leaves yuicompressor.jar
unset. If that's the case, don't define the compressor tasks. -->
<isset property="yuicompressor.jar"/>
<then>
<taskdef name="yuicompressor"
classname="com.yahoo.platform.yui.compressor.CompressorTask"
classpath="${yuicompressor.jar}"/>
<!-- Maps the legacy yuicompress task into a yuicompressor task. -->
<macrodef name="yuicompress">
<attribute name="src" />
<attribute name="dest" />
<attribute name="args" />
<!-- Unused. Type is detected automatically from the @{src} filename. -->
<attribute name="type" default="?"/>
<!-- If you had to override this, use the type option in args instead. -->
<sequential>
<yuicompressor input="@{src}" output="@{dest}" options="@{args}"/>
</sequential>
</macrodef>
</then>
</if>
+ <macrodef name="yuicoverage">
+ <attribute name="dest" />
+ <attribute name="src" />
+ <sequential>
+ <java jar="${yuitest-coverage.jar}" failonerror="true" fork="true">
+ <arg value="--charset" />
+ <arg value="utf8" />
+ <arg value="-o" />
+ <arg path="@{dest}" />
+ <arg path="@{src}" />
+ </java>
+ </sequential>
+ </macrodef>
+
<macrodef name="concatsource">
<attribute name="destfile" />
<attribute name="sourcedir" />
<attribute name="sourcefiles" />
<attribute name="workingdir" default="${workingdir}" />
<element name="filters" optional="true" description="Additonal filters to apply to individual files"/>
<sequential>
<echo level="verbose">Concatenating</echo>
<echo level="verbose"> Source Files : @{sourcefiles}</echo>
<echo level="verbose"> In Source Dir : @{sourcedir}</echo>
<echo level="verbose"> To : @{destfile}</echo>
<delete dir="@{workingdir}" quiet="true"/>
<copy todir="@{workingdir}">
<filelist dir="@{sourcedir}" files="@{sourcefiles}" />
<filterchain>
<filters />
<fixcrlf fixlast="true" eof="remove"/>
</filterchain>
</copy>
<concat destfile="@{destfile}" fixlastline="true">
<filelist dir="@{workingdir}" files="@{sourcefiles}" />
</concat>
<delete dir="${workingdir}" quiet="true" />
</sequential>
</macrodef>
<macrodef name="jslint">
<element name="jsfiles" optional="false" />
<sequential>
<pathconvert pathsep="' '" property="jsfileargs">
<jsfiles />
</pathconvert>
<if>
<not>
<or>
<istrue value="${jshint.online}"/>
<istrue value="${jshint.skip}"/>
</or>
</not>
<then>
<trycatch>
<try>
<exec executable="jshint" failifexecutionfails="true" outputproperty="jshint.version">
<arg line="--version"/>
</exec>
</try>
<catch>
<echo level="debug">Failed to get jshint version. Assuming it's not installed.</echo>
</catch>
</trycatch>
</then>
</if>
<if>
<or>
<isset property="jshint.version"/>
<istrue value="${jshint.online}"/>
</or>
<then>
<property name="jshint.online" value="true"/>
<exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.results" resultproperty="jshint.resultcode" errorproperty="jshint.error" logError="false">
<arg line="'${jsfileargs}'"/>
</exec>
<if>
<equals arg1="${jshint.resultcode}" arg2="1" forcestring="true"/>
<then>
<echo>Using JSHint Version: ${jshint.version}</echo>
<echo>${jshint.results}</echo>
<echo></echo>
</then>
</if>
</then>
<else>
<if>
<or>
<istrue value="${node.online}"/>
<http url="${node.jslint.url}"/>
</or>
<then>
<property name="node.online" value="true"/>
<post to="${node.jslint.url}" property="node.jslint.response" failonerror="${lint.failonerror}" verbose="false">
<prop name="files" value="${jsfileargs}"/>
<prop name="failonerror" value="${lint.failonerror}"/>
</post>
<!-- Since Ant doesn't really failonerror for the post task,
handle this ourselves: -->
<if>
<not>
<isset property="node.jslint.response"/>
</not>
<then>
<fail>JSLint failed. To view lint output and continue the build, run ant with -Dlint.failonerror=false.</fail>
</then>
<else>
<echo>${node.jslint.response}</echo>
</else>
</if>
<!-- Clear property for next run: -->
<var name="node.jslint.response" unset="true"/>
</then>
<else>
<echo>Using Rhino. Install nodejs to improve jslint speed, or skip with -Dlint.skip=true</echo>
<!--
Need to find a way to convert fileset to args (script?) to
avoid ' ', which will break for files with ' in them
Evaluates to the following java execution line...
java -r js.jar jslintconsole.js 'file1.js' 'file2.js' 'file3.js'
-->
<java jar="${rhino.jar}" fork="true" failonerror="${jslint.failonerror}">
<arg file="${jslintconsole.js}" />
<arg value="${jslintsrc.js}" />
<arg line="'${jsfileargs}'" />
</java>
</else>
</if>
</else>
</if>
</sequential>
</macrodef>
<macrodef name="registerversion">
<attribute name="module" />
<attribute name="classname" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/versioncode.txt" property="@{module}-@{classname}-version" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
<token key="CLASSNAME" value="@{classname}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="verbose">Adding Version Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}-@{classname}-version}</concat>
</sequential>
</macrodef>
<macrodef name="addlang">
<attribute name="dir" />
<attribute name="module" />
<attribute name="dest" />
<attribute name="lang" default="" />
<attribute name="details" default = ""/>
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}@{lang}_details" value="" />
</then>
<else>
<property name="@{module}@{lang}_details" value=",@{details}" />
</else>
</if>
<if>
<equals arg1="@{lang}" arg2="" />
<then>
<property name="@{module}@{lang}_fullname" value="@{module}" />
</then>
<else>
<property name="@{module}@{lang}_fullname" value="@{module}_@{lang}" />
</else>
</if>
<if>
<available file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<then>
<mkdir dir="${component.langbuilddir}" />
<java jar="${rhino.jar}" fork="true" failonerror="true">
<jvmarg value="-Dfile.encoding=utf-8" />
<arg file="${yrb2jsonconsole.js}" />
<arg file="${yrb2jsonsrc.js}" />
<arg file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<arg file="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" />
</java>
<echo level="verbose">Wrapping ${component.langbuilddir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</then>
<else>
<echo level="verbose">Wrapping @{dir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="@{dir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</else>
</if>
<copy file="${builddir}/files/langtemplate.txt" tofile="@{dest}/${@{module}@{lang}_fullname}.js" overwrite="true" outputencoding="utf-8">
<filterset>
<filter token="LANG" value="@{lang}" />
<filter token="LANG_MODULE" value="lang/${@{module}@{lang}_fullname}" />
<filter token="STRINGS" value="${@{module}@{lang}-strs-loaded}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="LANG_DETAILS" value="${@{module}@{lang}_details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addmodule">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="verbose">Wrapping @{file} in YUI.add module</echo>
<copy file="${builddir}/files/moduletemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="DETAILS" value="${@{module}-details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addrollup">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="verbose">Adding Rollup @{file} using YUI.add</echo>
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}"/>
<filter token="DETAILS" value="${@{module}-details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addlangrollup">
<attribute name="module" />
<attribute name="dir" />
<sequential>
<echo level="verbose">Registering rollup info for lang files in @{dir} using YUI.add</echo>
<for list="${component.rollup.lang}" param="lang" trim="true">
<sequential>
<loadfile srcfile="@{dir}/@{module}_@{lang}.js" property="@{module}-@{lang}-code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}_@{lang}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}-@{lang}-details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}_@{lang}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{lang}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}_@{lang}"/>
<filter token="DETAILS" value=", ${@{module}-@{lang}-details}"/>
</filterset>
</copy>
</sequential>
</for>
<loadfile srcfile="@{dir}/@{module}.js" property="@{module}--code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}--details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}--code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}"/>
<filter token="DETAILS" value=", ${@{module}--details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="stampcss">
<attribute name="module" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/css-stamp.txt" property="@{module}" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="verbose">Adding CSS Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}}</concat>
</sequential>
</macrodef>
</project>
diff --git a/componentbuild/shared/properties.xml b/componentbuild/shared/properties.xml
index d678a21..6843057 100644
--- a/componentbuild/shared/properties.xml
+++ b/componentbuild/shared/properties.xml
@@ -1,185 +1,186 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiSharedProperties">
<!-- ANT contrib library for loops, if/else support, with property fix for FOR task -->
<taskdef resource="antcontrib.properties">
<classpath>
<pathelement location="${builddir}/lib/ant-contrib/ant-contrib-1.0b3-modified.jar" />
</classpath>
</taskdef>
<dirname property="buildfile.dir" file="${ant.file}" />
<!--
builddir : The path to the builder/componentbuild directory from the component build file
srcdir : The path to top of the project source directory (e.g. yui2) from the component build file
-->
<property name="builddir" location="../../../builder/componentbuild" />
<property name="srcdir" location="../.." />
<!-- buildfiles.eol : End of line char to use for built files -->
<property name="buildfiles.eol" value="lf"/>
<!-- Supporting Tools -->
<property name="rhino.jar" location="${builddir}/lib/rhino/js.jar" />
<property name="jslintconsole.js" location="${builddir}/lib/jslint/jslint-console.js" />
<property name="jslintsrc.js" location="${builddir}/lib/jslint/fulljslint.js" />
<property name="yuicompressor.jar" location="${builddir}/lib/yuicompressor/ant-yuicompressor-2.4.5pre2.jar" />
+ <property name="yuitest-coverage.jar" location="${builddir}/lib/yuitest-coverage/yuitest-coverage.jar" />
<property name="yrb2jsonconsole.js" location="${builddir}/lib/yrb2json/yrb2json-console.js" />
<property name="yrb2jsonsrc.js" location="${builddir}/lib/yrb2json/yrb2json.js" />
<!-- YUI Compressor arguments for JS and CSS files -->
<property name="yuicompressor.js.charset" value="utf-8" />
<property name="yuicompressor.css.charset" value="utf-8" />
<property name="yuicompressor.js.args" value="--disable-optimizations --preserve-semi --line-break 6000" />
<property name="yuicompressor.css.args" value="--line-break 6000" />
<!-- Enable/Disable YUI Compressor verbosity. NOTE: Checked in build files should not disable this flag -->
<property name="yuicompressor.js.verbose" value="true" />
<property name="yuicompressor.css.verbose" value="true" />
<condition property="yuicompressor.js.args.internal" value="-v --charset ${yuicompressor.js.charset} ${yuicompressor.js.args}" else="--charset ${yuicompressor.js.charset} ${yuicompressor.js.args}">
<istrue value="${yuicompressor.js.verbose}" />
</condition>
<condition property="yuicompressor.css.args.internal" value="-v --charset ${yuicompressor.css.charset} ${yuicompressor.css.args}" else="--charset ${yuicompressor.css.charset} ${yuicompressor.css.args}">
<istrue value="${yuicompressor.css.verbose}" />
</condition>
<!-- Top Level Build Directories (e.g. yui2/build, yui3/build)-->
<property name="global.build.base" location="${srcdir}/build" />
<property name="global.build.component" location="${global.build.base}/${component}" />
<property name="global.build.component.assets" location="${global.build.component}/assets" />
<!-- Component Properties -->
<property name="component.module" value="${component}" />
<property name="component.basedir" location="${buildfile.dir}" />
<property name="component.jsfiles.base" location="${component.basedir}/js" />
<property name="component.cssfiles.base" location="${component.basedir}/css" />
<property name="component.lang.base" location="${component.basedir}/lang" />
<property name="component.assets.flatten" value="true" />
<property name="component.assets.base" location="${component.basedir}/assets" />
<property name="component.assets.files" value="**/*" />
<property name="component.assets.legacy.flatten" value="true" />
<property name="component.assets.legacy.base" location="${component.assets.base}/legacy" />
<property name="component.assets.legacy.files" value="**/*" />
<property name="component.assets.skins.base" location="${component.assets.base}/skins" />
<property name="component.assets.skins.files" value="**/*" />
<condition property="component.skins.exist">
<and>
<available file="${component.assets.base}/${component}-core.css" type="file" />
<available file="${component.assets.base}/skins" type="dir" />
</and>
</condition>
<!-- component is part of a rollup build, so rollup skins to parent -->
<condition property="rollupskins">
<and>
<istrue value="${rollup}" />
<istrue value="${component.skins.exist}" />
</and>
</condition>
<available file="${component.assets.base}" type="dir" property="component.assets.exist"/>
<condition property="component.langs.exist">
<and>
<or>
<isset property="component.lang" />
<isset property="component.rollup.lang" />
</or>
</and>
</condition>
<condition property="rolluplangs">
<and>
<istrue value="${rollup}" />
<istrue value="${component.langs.exist}" />
</and>
</condition>
<!-- component test module properties -->
<property name="testsdir" value="./tests"/>
<property name="tests.srcdir" value="${testsdir}/src"/>
<property name="tests.builddir" value="${testsdir}"/>
<property name="tests.component" value="${component}-tests"/>
<property name="tests.jsfiles" value="${component}.js"/>
<property name="tests.requires" value="${component}, test"/>
<if>
<istrue value="${component.rollup}"/>
<then>
<propertyregex property="tests.rollup.modules"
override="true"
input="${component.use}"
casesensitive="false"
regexp="([^\,\s]+)"
replace="\1-tests"
/>
</then>
</if>
<!--
DEPRECATED: component.basefilename and component.releasetype are deprecated
We used to mark filenames with suffixes (-beta, -experimental), which we no longer do
-->
<condition property="component.basefilename" value="${component}" else="${component}">
<isset property="component.releasetype"/>
</condition>
<!-- Default logger regex values if not provided -->
<property name="component.logger.regex" value="^.*?(?:logger|YAHOO.log).*?(?:;|\).*;|(?:\r?\n.*?)*?\).*;).*;?.*?\r?\n" />
<property name="component.logger.regex.replace" value="" />
<property name="component.logger.regex.flags" value="mg" />
<property name="component.logger.regex.byline" value="false" />
<!-- Rollup support, currently only used for YUI 3 -->
<property name="component.rollup" value="false"/>
<property name="component.rollup.target" value="all"/>
<condition property="component.builddir" value="${component.basedir}/build_rollup_tmp" else="${component.basedir}/build_tmp">
<istrue value="${component.rollup}"/>
</condition>
<condition property="rollup.skins.exist">
<and>
<istrue value="${component.rollup}" />
<available file="${component.assets.base}/skins" type="dir" />
</and>
</condition>
<condition property="skins.exist">
<or>
<istrue value="${rollup.skins.exist}" />
<istrue value="${component.skins.exist}" />
</or>
</condition>
<!-- The temporary working directory used by the build process -->
<property name="workingdir" location="${component.builddir}/ant" />
<!-- Directory for language resource bundles in JSON format derived from YRB format -->
<property name="component.langbuilddir" value="${component.basedir}/build_lang_tmp" />
<!-- The file which defines the default targets for the particular type of component (module, rollup, css) -->
<condition property="targetbase" value="rollup" else="module">
<istrue value="${component.rollup}"/>
</condition>
<condition property="targets" value="../shared/cssmodule.xml" else="${targetbase}.xml">
<isset property="component.cssfiles" />
</condition>
<property name="lint.failonerror" value="false"/>
<property name="node.jslint.url" value="http://127.0.0.1:8081/"/>
<property name="yuicompressor.url" value="http://127.0.0.1:${yuicompressor.port}/compress"/>
</project>
|
yui/builder
|
1c1b87301fb79fc433bbe6207210bd10a512fb5d
|
Fixed node-jslint to work with Node.js 0.7.x (replaced sys.puts call with console.log)
|
diff --git a/componentbuild/lib/jslint/jslint-node.js b/componentbuild/lib/jslint/jslint-node.js
index 2b1e652..bc7646f 100644
--- a/componentbuild/lib/jslint/jslint-node.js
+++ b/componentbuild/lib/jslint/jslint-node.js
@@ -1,127 +1,127 @@
/**
* Javascript Shell Script to Load and JSLint js files through Rhino Javascript Shell
* The jslint source file is expected as the first argument, followed by the list of JS files to JSLint
*
* e.g.
* java -j js.jar /tools/fulljslint.js testFile1.js testFile2.js testFile3.js
**/
JSLINT = require("./fulljslint").JSLINT;
(function(){ // Just to keep stuff seperate from JSLINT code
var PORT = parseInt(process.argv[2]) || 8081;
var OPTS = {
browser : true,
//laxLineEnd : true,
undef: true,
newcap: false,
predef:["YUI", "window", "YUI_config", "YAHOO", "YAHOO_config", "Event",
"opera", "exports", "document", "navigator", "console", "self", "require",
"module", "process", "__dirname", "__filename"]
};
function test(js, file) {
var body = "", code = 200;
var success = JSLINT(js, OPTS);
if (success) {
return {
"content": '\t[JSLINT] [OK] ' + file,
code: code
};
} else {
if (JSLINT.errors.length) {
body += '[JSLINT] ' + file + '\n';
body += '----------------------------------------------------------\n';
for (var i=0; i < JSLINT.errors.length; ++i) {
var e = JSLINT.errors[i];
if (e) {
body += ("\t" + e.line + ", " + e.character + ": " + e.reason + "\n\t" + clean(e.evidence) + "\n");
}
}
body += '----------------------------------------------------------\n';
}
// Last item is null if JSLint hit a fatal error
if (JSLINT.errors && JSLINT.errors[JSLINT.errors.length-1] === null) {
code = 500;
}
return {
"content" : body,
"code" : code
};
}
}
function clean(str) {
var trimmed = "";
if (str) {
if(str.length <= 500) {
trimmed = str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
} else {
trimmed = "[Code Evidence Omitted: Greater than 500 chars]";
}
}
return trimmed;
}
var qs = require("querystring");
var fs = require("fs");
var EventEmitter = require("events").EventEmitter;
var ticket = 0;
require("http").createServer(function (req, res) {
var data = "";
req.addListener("data", function (chunk) {
data += chunk;
});
var proc = new EventEmitter();
proc.addListener("end", function (code, body, die) {
res.writeHead(code, {"Content-type" : "text/plain"});
res.end(body);
if (die) process.exit(0);
});
req.addListener("end", function () {
ticket++;
var code = 200, body;
var die = "/kill" === req.url;
if (die) body = "Goodbye.";
else if (req.method === "POST") {
var query = qs.parse(data);
var files = query["files"].split("' '");
var failOnError = query["failonerror"] == "true";
var results = [];
files.forEach(function (file) {
fs.readFile(file, function (err, data) {
var diagnosis = test(data.toString("utf8"), file);
results.push(diagnosis.content);
code = (
failOnError &&
diagnosis.code !== 200
) ? diagnosis.code : code;
if (results.length == files.length) proc.emit("end", code, results.join("\n"));
});
});
} else {
body = "Ready.";
}
if (body) proc.emit("end", code, body, die);
});
}).listen(PORT, "127.0.0.1");
- require("sys").puts("Server started on port " + PORT);
+ console.log("Server started on port " + PORT);
(function () {
var reap;
setInterval(function () {
if (reap == ticket) process.exit(0);
reap = ticket;
}, 10000);
})();
})();
|
yui/builder
|
515dd8613201595a8a37947f01330f0312566e03
|
Removed exception in default/quiet mode when sniffing for jshint
|
diff --git a/componentbuild/shared/macrolib.xml b/componentbuild/shared/macrolib.xml
index 89578b0..65870d4 100644
--- a/componentbuild/shared/macrolib.xml
+++ b/componentbuild/shared/macrolib.xml
@@ -1,446 +1,445 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiMacroLib">
<macrodef name="arrayliteral">
<attribute name="from" />
<attribute name="to" />
<attribute name="key" />
<sequential>
<if>
<and>
<isset property="@{from}" />
<length string="${@{from}}" when="ne" length="0" />
</and>
<then>
<propertyregex property="array"
override="true"
input="${@{from}}"
casesensitive="false"
regexp="([^\,\s]+)"
replace="'\1'"
/>
<property name="@{to}" value="@{key}:[${array}]" />
</then>
</if>
</sequential>
</macrodef>
<macrodef name="createdetails">
<sequential>
<arrayliteral from="component.use" to="component.details.use" key="use" />
<arrayliteral from="component.supersedes" to="component.details.supersedes" key="supersedes" />
<arrayliteral from="component.requires" to="component.details.requires" key="requires" />
<arrayliteral from="component.optional" to="component.details.optional" key="optional" />
<arrayliteral from="component.after" to="component.details.after" key="after" />
<arrayliteral from="component.lang" to="component.details.lang" key="lang" />
<if>
<isset property="component.skinnable" />
<then>
<property name="component.details.skinnable" value="skinnable:${component.skinnable}" />
</then>
</if>
<propertyselector property="details.list"
delimiter=","
match="component\.details.([^\.]*)"
select="\1"
casesensitive="false" />
<var name="details" value="" />
<if>
<isset property="details.list" />
<then>
<for list="${details.list}" param="val">
<sequential>
<var name="details" value="${component.details.@{val}}, ${details}" />
</sequential>
</for>
<propertyregex property="component.details.hash"
input="{${details}}"
regexp="(\,\s*?\})"
replace="}"
casesensitive="false" />
</then>
<else>
<property name="component.details.hash" value="" />
</else>
</if>
</sequential>
</macrodef>
<if>
<!-- The yui2 builder-integration script embeds macrolib.xml
by itself for other macros, which leaves yuicompressor.jar
unset. If that's the case, don't define the compressor tasks. -->
<isset property="yuicompressor.jar"/>
<then>
<taskdef name="yuicompressor"
classname="com.yahoo.platform.yui.compressor.CompressorTask"
classpath="${yuicompressor.jar}"/>
<!-- Maps the legacy yuicompress task into a yuicompressor task. -->
<macrodef name="yuicompress">
<attribute name="src" />
<attribute name="dest" />
<attribute name="args" />
<!-- Unused. Type is detected automatically from the @{src} filename. -->
<attribute name="type" default="?"/>
<!-- If you had to override this, use the type option in args instead. -->
<sequential>
<yuicompressor input="@{src}" output="@{dest}" options="@{args}"/>
</sequential>
</macrodef>
</then>
</if>
<macrodef name="concatsource">
<attribute name="destfile" />
<attribute name="sourcedir" />
<attribute name="sourcefiles" />
<attribute name="workingdir" default="${workingdir}" />
<element name="filters" optional="true" description="Additonal filters to apply to individual files"/>
<sequential>
<echo level="verbose">Concatenating</echo>
<echo level="verbose"> Source Files : @{sourcefiles}</echo>
<echo level="verbose"> In Source Dir : @{sourcedir}</echo>
<echo level="verbose"> To : @{destfile}</echo>
<delete dir="@{workingdir}" quiet="true"/>
<copy todir="@{workingdir}">
<filelist dir="@{sourcedir}" files="@{sourcefiles}" />
<filterchain>
<filters />
<fixcrlf fixlast="true" eof="remove"/>
</filterchain>
</copy>
<concat destfile="@{destfile}" fixlastline="true">
<filelist dir="@{workingdir}" files="@{sourcefiles}" />
</concat>
<delete dir="${workingdir}" quiet="true" />
</sequential>
</macrodef>
<macrodef name="jslint">
<element name="jsfiles" optional="false" />
<sequential>
<pathconvert pathsep="' '" property="jsfileargs">
<jsfiles />
</pathconvert>
<if>
<not>
<or>
<istrue value="${jshint.online}"/>
<istrue value="${jshint.skip}"/>
</or>
</not>
<then>
- <exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.version">
- <arg line="--version"/>
- </exec>
- </then>
- </if>
- <if>
- <not>
- <isset property="jshint.version"/>
- </not>
- <then>
- <echo>Ignore the `java.io.IOException`, that means it can't find `jshint`. We will use Node.js instead of `jshint`</echo>
+ <trycatch>
+ <try>
+ <exec executable="jshint" failifexecutionfails="true" outputproperty="jshint.version">
+ <arg line="--version"/>
+ </exec>
+ </try>
+ <catch>
+ <echo level="debug">Failed to get jshint version. Assuming it's not installed.</echo>
+ </catch>
+ </trycatch>
</then>
</if>
<if>
<or>
<isset property="jshint.version"/>
<istrue value="${jshint.online}"/>
</or>
<then>
<property name="jshint.online" value="true"/>
<exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.results" resultproperty="jshint.resultcode" errorproperty="jshint.error" logError="false">
<arg line="'${jsfileargs}'"/>
</exec>
<if>
<equals arg1="${jshint.resultcode}" arg2="1" forcestring="true"/>
<then>
<echo>Using JSHint Version: ${jshint.version}</echo>
<echo>${jshint.results}</echo>
<echo></echo>
</then>
</if>
</then>
<else>
<if>
<or>
<istrue value="${node.online}"/>
<http url="${node.jslint.url}"/>
</or>
<then>
<property name="node.online" value="true"/>
<post to="${node.jslint.url}" property="node.jslint.response" failonerror="${lint.failonerror}" verbose="false">
<prop name="files" value="${jsfileargs}"/>
<prop name="failonerror" value="${lint.failonerror}"/>
</post>
<!-- Since Ant doesn't really failonerror for the post task,
handle this ourselves: -->
<if>
<not>
<isset property="node.jslint.response"/>
</not>
<then>
<fail>JSLint failed. To view lint output and continue the build, run ant with -Dlint.failonerror=false.</fail>
</then>
<else>
<echo>${node.jslint.response}</echo>
</else>
</if>
<!-- Clear property for next run: -->
<var name="node.jslint.response" unset="true"/>
</then>
<else>
<echo>Using Rhino. Install nodejs to improve jslint speed, or skip with -Dlint.skip=true</echo>
<!--
Need to find a way to convert fileset to args (script?) to
avoid ' ', which will break for files with ' in them
Evaluates to the following java execution line...
java -r js.jar jslintconsole.js 'file1.js' 'file2.js' 'file3.js'
-->
<java jar="${rhino.jar}" fork="true" failonerror="${jslint.failonerror}">
<arg file="${jslintconsole.js}" />
<arg value="${jslintsrc.js}" />
<arg line="'${jsfileargs}'" />
</java>
</else>
</if>
</else>
</if>
</sequential>
</macrodef>
<macrodef name="registerversion">
<attribute name="module" />
<attribute name="classname" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/versioncode.txt" property="@{module}-@{classname}-version" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
<token key="CLASSNAME" value="@{classname}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="verbose">Adding Version Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}-@{classname}-version}</concat>
</sequential>
</macrodef>
<macrodef name="addlang">
<attribute name="dir" />
<attribute name="module" />
<attribute name="dest" />
<attribute name="lang" default="" />
<attribute name="details" default = ""/>
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}@{lang}_details" value="" />
</then>
<else>
<property name="@{module}@{lang}_details" value=",@{details}" />
</else>
</if>
<if>
<equals arg1="@{lang}" arg2="" />
<then>
<property name="@{module}@{lang}_fullname" value="@{module}" />
</then>
<else>
<property name="@{module}@{lang}_fullname" value="@{module}_@{lang}" />
</else>
</if>
<if>
<available file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<then>
<mkdir dir="${component.langbuilddir}" />
<java jar="${rhino.jar}" fork="true" failonerror="true">
<jvmarg value="-Dfile.encoding=utf-8" />
<arg file="${yrb2jsonconsole.js}" />
<arg file="${yrb2jsonsrc.js}" />
<arg file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<arg file="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" />
</java>
<echo level="verbose">Wrapping ${component.langbuilddir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</then>
<else>
<echo level="verbose">Wrapping @{dir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="@{dir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</else>
</if>
<copy file="${builddir}/files/langtemplate.txt" tofile="@{dest}/${@{module}@{lang}_fullname}.js" overwrite="true" outputencoding="utf-8">
<filterset>
<filter token="LANG" value="@{lang}" />
<filter token="LANG_MODULE" value="lang/${@{module}@{lang}_fullname}" />
<filter token="STRINGS" value="${@{module}@{lang}-strs-loaded}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="LANG_DETAILS" value="${@{module}@{lang}_details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addmodule">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="verbose">Wrapping @{file} in YUI.add module</echo>
<copy file="${builddir}/files/moduletemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="DETAILS" value="${@{module}-details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addrollup">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="verbose">Adding Rollup @{file} using YUI.add</echo>
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}"/>
<filter token="DETAILS" value="${@{module}-details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addlangrollup">
<attribute name="module" />
<attribute name="dir" />
<sequential>
<echo level="verbose">Registering rollup info for lang files in @{dir} using YUI.add</echo>
<for list="${component.rollup.lang}" param="lang" trim="true">
<sequential>
<loadfile srcfile="@{dir}/@{module}_@{lang}.js" property="@{module}-@{lang}-code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}_@{lang}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}-@{lang}-details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}_@{lang}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{lang}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}_@{lang}"/>
<filter token="DETAILS" value=", ${@{module}-@{lang}-details}"/>
</filterset>
</copy>
</sequential>
</for>
<loadfile srcfile="@{dir}/@{module}.js" property="@{module}--code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}--details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}--code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}"/>
<filter token="DETAILS" value=", ${@{module}--details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="stampcss">
<attribute name="module" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/css-stamp.txt" property="@{module}" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="verbose">Adding CSS Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}}</concat>
</sequential>
</macrodef>
</project>
|
yui/builder
|
e575c5792060a1ceab2fb82f787cc93f493a14a5
|
Print a note that jshint wasn't found and explain the java.io.IOExpection warning
|
diff --git a/componentbuild/shared/macrolib.xml b/componentbuild/shared/macrolib.xml
index 54d8fc2..89578b0 100644
--- a/componentbuild/shared/macrolib.xml
+++ b/componentbuild/shared/macrolib.xml
@@ -1,438 +1,446 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiMacroLib">
<macrodef name="arrayliteral">
<attribute name="from" />
<attribute name="to" />
<attribute name="key" />
<sequential>
<if>
<and>
<isset property="@{from}" />
<length string="${@{from}}" when="ne" length="0" />
</and>
<then>
<propertyregex property="array"
override="true"
input="${@{from}}"
casesensitive="false"
regexp="([^\,\s]+)"
replace="'\1'"
/>
<property name="@{to}" value="@{key}:[${array}]" />
</then>
</if>
</sequential>
</macrodef>
<macrodef name="createdetails">
<sequential>
<arrayliteral from="component.use" to="component.details.use" key="use" />
<arrayliteral from="component.supersedes" to="component.details.supersedes" key="supersedes" />
<arrayliteral from="component.requires" to="component.details.requires" key="requires" />
<arrayliteral from="component.optional" to="component.details.optional" key="optional" />
<arrayliteral from="component.after" to="component.details.after" key="after" />
<arrayliteral from="component.lang" to="component.details.lang" key="lang" />
<if>
<isset property="component.skinnable" />
<then>
<property name="component.details.skinnable" value="skinnable:${component.skinnable}" />
</then>
</if>
<propertyselector property="details.list"
delimiter=","
match="component\.details.([^\.]*)"
select="\1"
casesensitive="false" />
<var name="details" value="" />
<if>
<isset property="details.list" />
<then>
<for list="${details.list}" param="val">
<sequential>
<var name="details" value="${component.details.@{val}}, ${details}" />
</sequential>
</for>
<propertyregex property="component.details.hash"
input="{${details}}"
regexp="(\,\s*?\})"
replace="}"
casesensitive="false" />
</then>
<else>
<property name="component.details.hash" value="" />
</else>
</if>
</sequential>
</macrodef>
<if>
<!-- The yui2 builder-integration script embeds macrolib.xml
by itself for other macros, which leaves yuicompressor.jar
unset. If that's the case, don't define the compressor tasks. -->
<isset property="yuicompressor.jar"/>
<then>
<taskdef name="yuicompressor"
classname="com.yahoo.platform.yui.compressor.CompressorTask"
classpath="${yuicompressor.jar}"/>
<!-- Maps the legacy yuicompress task into a yuicompressor task. -->
<macrodef name="yuicompress">
<attribute name="src" />
<attribute name="dest" />
<attribute name="args" />
<!-- Unused. Type is detected automatically from the @{src} filename. -->
<attribute name="type" default="?"/>
<!-- If you had to override this, use the type option in args instead. -->
<sequential>
<yuicompressor input="@{src}" output="@{dest}" options="@{args}"/>
</sequential>
</macrodef>
</then>
</if>
<macrodef name="concatsource">
<attribute name="destfile" />
<attribute name="sourcedir" />
<attribute name="sourcefiles" />
<attribute name="workingdir" default="${workingdir}" />
<element name="filters" optional="true" description="Additonal filters to apply to individual files"/>
<sequential>
<echo level="verbose">Concatenating</echo>
<echo level="verbose"> Source Files : @{sourcefiles}</echo>
<echo level="verbose"> In Source Dir : @{sourcedir}</echo>
<echo level="verbose"> To : @{destfile}</echo>
<delete dir="@{workingdir}" quiet="true"/>
<copy todir="@{workingdir}">
<filelist dir="@{sourcedir}" files="@{sourcefiles}" />
<filterchain>
<filters />
<fixcrlf fixlast="true" eof="remove"/>
</filterchain>
</copy>
<concat destfile="@{destfile}" fixlastline="true">
<filelist dir="@{workingdir}" files="@{sourcefiles}" />
</concat>
<delete dir="${workingdir}" quiet="true" />
</sequential>
</macrodef>
<macrodef name="jslint">
<element name="jsfiles" optional="false" />
<sequential>
<pathconvert pathsep="' '" property="jsfileargs">
<jsfiles />
</pathconvert>
<if>
<not>
<or>
<istrue value="${jshint.online}"/>
<istrue value="${jshint.skip}"/>
</or>
</not>
<then>
<exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.version">
<arg line="--version"/>
</exec>
</then>
</if>
+ <if>
+ <not>
+ <isset property="jshint.version"/>
+ </not>
+ <then>
+ <echo>Ignore the `java.io.IOException`, that means it can't find `jshint`. We will use Node.js instead of `jshint`</echo>
+ </then>
+ </if>
<if>
<or>
<isset property="jshint.version"/>
<istrue value="${jshint.online}"/>
</or>
<then>
<property name="jshint.online" value="true"/>
<exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.results" resultproperty="jshint.resultcode" errorproperty="jshint.error" logError="false">
<arg line="'${jsfileargs}'"/>
</exec>
<if>
<equals arg1="${jshint.resultcode}" arg2="1" forcestring="true"/>
<then>
<echo>Using JSHint Version: ${jshint.version}</echo>
<echo>${jshint.results}</echo>
<echo></echo>
</then>
</if>
</then>
<else>
<if>
<or>
<istrue value="${node.online}"/>
<http url="${node.jslint.url}"/>
</or>
<then>
<property name="node.online" value="true"/>
<post to="${node.jslint.url}" property="node.jslint.response" failonerror="${lint.failonerror}" verbose="false">
<prop name="files" value="${jsfileargs}"/>
<prop name="failonerror" value="${lint.failonerror}"/>
</post>
<!-- Since Ant doesn't really failonerror for the post task,
handle this ourselves: -->
<if>
<not>
<isset property="node.jslint.response"/>
</not>
<then>
<fail>JSLint failed. To view lint output and continue the build, run ant with -Dlint.failonerror=false.</fail>
</then>
<else>
<echo>${node.jslint.response}</echo>
</else>
</if>
<!-- Clear property for next run: -->
<var name="node.jslint.response" unset="true"/>
</then>
<else>
<echo>Using Rhino. Install nodejs to improve jslint speed, or skip with -Dlint.skip=true</echo>
<!--
Need to find a way to convert fileset to args (script?) to
avoid ' ', which will break for files with ' in them
Evaluates to the following java execution line...
java -r js.jar jslintconsole.js 'file1.js' 'file2.js' 'file3.js'
-->
<java jar="${rhino.jar}" fork="true" failonerror="${jslint.failonerror}">
<arg file="${jslintconsole.js}" />
<arg value="${jslintsrc.js}" />
<arg line="'${jsfileargs}'" />
</java>
</else>
</if>
</else>
</if>
</sequential>
</macrodef>
<macrodef name="registerversion">
<attribute name="module" />
<attribute name="classname" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/versioncode.txt" property="@{module}-@{classname}-version" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
<token key="CLASSNAME" value="@{classname}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="verbose">Adding Version Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}-@{classname}-version}</concat>
</sequential>
</macrodef>
<macrodef name="addlang">
<attribute name="dir" />
<attribute name="module" />
<attribute name="dest" />
<attribute name="lang" default="" />
<attribute name="details" default = ""/>
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}@{lang}_details" value="" />
</then>
<else>
<property name="@{module}@{lang}_details" value=",@{details}" />
</else>
</if>
<if>
<equals arg1="@{lang}" arg2="" />
<then>
<property name="@{module}@{lang}_fullname" value="@{module}" />
</then>
<else>
<property name="@{module}@{lang}_fullname" value="@{module}_@{lang}" />
</else>
</if>
<if>
<available file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<then>
<mkdir dir="${component.langbuilddir}" />
<java jar="${rhino.jar}" fork="true" failonerror="true">
<jvmarg value="-Dfile.encoding=utf-8" />
<arg file="${yrb2jsonconsole.js}" />
<arg file="${yrb2jsonsrc.js}" />
<arg file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<arg file="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" />
</java>
<echo level="verbose">Wrapping ${component.langbuilddir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</then>
<else>
<echo level="verbose">Wrapping @{dir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="@{dir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</else>
</if>
<copy file="${builddir}/files/langtemplate.txt" tofile="@{dest}/${@{module}@{lang}_fullname}.js" overwrite="true" outputencoding="utf-8">
<filterset>
<filter token="LANG" value="@{lang}" />
<filter token="LANG_MODULE" value="lang/${@{module}@{lang}_fullname}" />
<filter token="STRINGS" value="${@{module}@{lang}-strs-loaded}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="LANG_DETAILS" value="${@{module}@{lang}_details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addmodule">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="verbose">Wrapping @{file} in YUI.add module</echo>
<copy file="${builddir}/files/moduletemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="DETAILS" value="${@{module}-details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addrollup">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="verbose">Adding Rollup @{file} using YUI.add</echo>
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}"/>
<filter token="DETAILS" value="${@{module}-details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addlangrollup">
<attribute name="module" />
<attribute name="dir" />
<sequential>
<echo level="verbose">Registering rollup info for lang files in @{dir} using YUI.add</echo>
<for list="${component.rollup.lang}" param="lang" trim="true">
<sequential>
<loadfile srcfile="@{dir}/@{module}_@{lang}.js" property="@{module}-@{lang}-code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}_@{lang}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}-@{lang}-details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}_@{lang}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{lang}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}_@{lang}"/>
<filter token="DETAILS" value=", ${@{module}-@{lang}-details}"/>
</filterset>
</copy>
</sequential>
</for>
<loadfile srcfile="@{dir}/@{module}.js" property="@{module}--code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}--details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}--code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}"/>
<filter token="DETAILS" value=", ${@{module}--details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="stampcss">
<attribute name="module" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/css-stamp.txt" property="@{module}" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="verbose">Adding CSS Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}}</concat>
</sequential>
</macrodef>
</project>
|
yui/builder
|
64bf74b7db826f89080c74ad15feedff02e05b9f
|
Made JSLint output look more like it ran
|
diff --git a/componentbuild/lib/jslint/jslint-node.js b/componentbuild/lib/jslint/jslint-node.js
index 8516c2b..2b1e652 100644
--- a/componentbuild/lib/jslint/jslint-node.js
+++ b/componentbuild/lib/jslint/jslint-node.js
@@ -1,127 +1,127 @@
/**
* Javascript Shell Script to Load and JSLint js files through Rhino Javascript Shell
* The jslint source file is expected as the first argument, followed by the list of JS files to JSLint
*
* e.g.
* java -j js.jar /tools/fulljslint.js testFile1.js testFile2.js testFile3.js
**/
JSLINT = require("./fulljslint").JSLINT;
(function(){ // Just to keep stuff seperate from JSLINT code
var PORT = parseInt(process.argv[2]) || 8081;
var OPTS = {
browser : true,
//laxLineEnd : true,
undef: true,
newcap: false,
predef:["YUI", "window", "YUI_config", "YAHOO", "YAHOO_config", "Event",
"opera", "exports", "document", "navigator", "console", "self", "require",
"module", "process", "__dirname", "__filename"]
};
function test(js, file) {
var body = "", code = 200;
var success = JSLINT(js, OPTS);
if (success) {
return {
- "content": '\t[OK] ' + file,
+ "content": '\t[JSLINT] [OK] ' + file,
code: code
};
} else {
if (JSLINT.errors.length) {
body += '[JSLINT] ' + file + '\n';
body += '----------------------------------------------------------\n';
for (var i=0; i < JSLINT.errors.length; ++i) {
var e = JSLINT.errors[i];
if (e) {
body += ("\t" + e.line + ", " + e.character + ": " + e.reason + "\n\t" + clean(e.evidence) + "\n");
}
}
body += '----------------------------------------------------------\n';
}
// Last item is null if JSLint hit a fatal error
if (JSLINT.errors && JSLINT.errors[JSLINT.errors.length-1] === null) {
code = 500;
}
return {
"content" : body,
"code" : code
};
}
}
function clean(str) {
var trimmed = "";
if (str) {
if(str.length <= 500) {
trimmed = str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
} else {
trimmed = "[Code Evidence Omitted: Greater than 500 chars]";
}
}
return trimmed;
}
var qs = require("querystring");
var fs = require("fs");
var EventEmitter = require("events").EventEmitter;
var ticket = 0;
require("http").createServer(function (req, res) {
var data = "";
req.addListener("data", function (chunk) {
data += chunk;
});
var proc = new EventEmitter();
proc.addListener("end", function (code, body, die) {
res.writeHead(code, {"Content-type" : "text/plain"});
res.end(body);
if (die) process.exit(0);
});
req.addListener("end", function () {
ticket++;
var code = 200, body;
var die = "/kill" === req.url;
if (die) body = "Goodbye.";
else if (req.method === "POST") {
var query = qs.parse(data);
var files = query["files"].split("' '");
var failOnError = query["failonerror"] == "true";
var results = [];
files.forEach(function (file) {
fs.readFile(file, function (err, data) {
var diagnosis = test(data.toString("utf8"), file);
results.push(diagnosis.content);
code = (
failOnError &&
diagnosis.code !== 200
) ? diagnosis.code : code;
if (results.length == files.length) proc.emit("end", code, results.join("\n"));
});
});
} else {
body = "Ready.";
}
if (body) proc.emit("end", code, body, die);
});
}).listen(PORT, "127.0.0.1");
require("sys").puts("Server started on port " + PORT);
(function () {
var reap;
setInterval(function () {
if (reap == ticket) process.exit(0);
reap = ticket;
}, 10000);
})();
})();
|
yui/builder
|
88e1c27c5382bb7e67c6429af1fd98d4925406c0
|
Changed logs to verbose instead of info, added support for local installed jshint CLI tool and only run jslint/hint on raw files by default
|
diff --git a/componentbuild/shared/macrolib.xml b/componentbuild/shared/macrolib.xml
index a06c6c9..54d8fc2 100644
--- a/componentbuild/shared/macrolib.xml
+++ b/componentbuild/shared/macrolib.xml
@@ -1,400 +1,438 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiMacroLib">
<macrodef name="arrayliteral">
<attribute name="from" />
<attribute name="to" />
<attribute name="key" />
<sequential>
<if>
<and>
<isset property="@{from}" />
<length string="${@{from}}" when="ne" length="0" />
</and>
<then>
<propertyregex property="array"
override="true"
input="${@{from}}"
casesensitive="false"
regexp="([^\,\s]+)"
replace="'\1'"
/>
<property name="@{to}" value="@{key}:[${array}]" />
</then>
</if>
</sequential>
</macrodef>
<macrodef name="createdetails">
<sequential>
<arrayliteral from="component.use" to="component.details.use" key="use" />
<arrayliteral from="component.supersedes" to="component.details.supersedes" key="supersedes" />
<arrayliteral from="component.requires" to="component.details.requires" key="requires" />
<arrayliteral from="component.optional" to="component.details.optional" key="optional" />
<arrayliteral from="component.after" to="component.details.after" key="after" />
<arrayliteral from="component.lang" to="component.details.lang" key="lang" />
<if>
<isset property="component.skinnable" />
<then>
<property name="component.details.skinnable" value="skinnable:${component.skinnable}" />
</then>
</if>
<propertyselector property="details.list"
delimiter=","
match="component\.details.([^\.]*)"
select="\1"
casesensitive="false" />
<var name="details" value="" />
<if>
<isset property="details.list" />
<then>
<for list="${details.list}" param="val">
<sequential>
<var name="details" value="${component.details.@{val}}, ${details}" />
</sequential>
</for>
<propertyregex property="component.details.hash"
input="{${details}}"
regexp="(\,\s*?\})"
replace="}"
casesensitive="false" />
</then>
<else>
<property name="component.details.hash" value="" />
</else>
</if>
</sequential>
</macrodef>
<if>
<!-- The yui2 builder-integration script embeds macrolib.xml
by itself for other macros, which leaves yuicompressor.jar
unset. If that's the case, don't define the compressor tasks. -->
<isset property="yuicompressor.jar"/>
<then>
<taskdef name="yuicompressor"
classname="com.yahoo.platform.yui.compressor.CompressorTask"
classpath="${yuicompressor.jar}"/>
<!-- Maps the legacy yuicompress task into a yuicompressor task. -->
<macrodef name="yuicompress">
<attribute name="src" />
<attribute name="dest" />
<attribute name="args" />
<!-- Unused. Type is detected automatically from the @{src} filename. -->
<attribute name="type" default="?"/>
<!-- If you had to override this, use the type option in args instead. -->
<sequential>
<yuicompressor input="@{src}" output="@{dest}" options="@{args}"/>
</sequential>
</macrodef>
</then>
</if>
<macrodef name="concatsource">
<attribute name="destfile" />
<attribute name="sourcedir" />
<attribute name="sourcefiles" />
<attribute name="workingdir" default="${workingdir}" />
<element name="filters" optional="true" description="Additonal filters to apply to individual files"/>
<sequential>
- <echo level="info">Concatenating</echo>
- <echo level="info"> Source Files : @{sourcefiles}</echo>
- <echo level="info"> In Source Dir : @{sourcedir}</echo>
- <echo level="info"> To : @{destfile}</echo>
+ <echo level="verbose">Concatenating</echo>
+ <echo level="verbose"> Source Files : @{sourcefiles}</echo>
+ <echo level="verbose"> In Source Dir : @{sourcedir}</echo>
+ <echo level="verbose"> To : @{destfile}</echo>
<delete dir="@{workingdir}" quiet="true"/>
<copy todir="@{workingdir}">
<filelist dir="@{sourcedir}" files="@{sourcefiles}" />
<filterchain>
<filters />
<fixcrlf fixlast="true" eof="remove"/>
</filterchain>
</copy>
<concat destfile="@{destfile}" fixlastline="true">
<filelist dir="@{workingdir}" files="@{sourcefiles}" />
</concat>
<delete dir="${workingdir}" quiet="true" />
</sequential>
</macrodef>
<macrodef name="jslint">
<element name="jsfiles" optional="false" />
<sequential>
<pathconvert pathsep="' '" property="jsfileargs">
<jsfiles />
</pathconvert>
+ <if>
+ <not>
+ <or>
+ <istrue value="${jshint.online}"/>
+ <istrue value="${jshint.skip}"/>
+ </or>
+ </not>
+ <then>
+ <exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.version">
+ <arg line="--version"/>
+ </exec>
+ </then>
+ </if>
<if>
<or>
- <istrue value="${node.online}"/>
- <http url="${node.jslint.url}"/>
+ <isset property="jshint.version"/>
+ <istrue value="${jshint.online}"/>
</or>
<then>
- <property name="node.online" value="true"/>
- <post to="${node.jslint.url}" property="node.jslint.response" failonerror="${lint.failonerror}">
- <prop name="files" value="${jsfileargs}"/>
- <prop name="failonerror" value="${lint.failonerror}"/>
- </post>
- <!-- Since Ant doesn't really failonerror for the post task,
- handle this ourselves: -->
+ <property name="jshint.online" value="true"/>
+ <exec executable="jshint" failifexecutionfails="false" outputproperty="jshint.results" resultproperty="jshint.resultcode" errorproperty="jshint.error" logError="false">
+ <arg line="'${jsfileargs}'"/>
+ </exec>
<if>
- <not>
- <isset property="node.jslint.response"/>
- </not>
+ <equals arg1="${jshint.resultcode}" arg2="1" forcestring="true"/>
<then>
- <fail>JSLint failed. To view lint output and continue the build, run ant with -Dlint.failonerror=false.</fail>
+ <echo>Using JSHint Version: ${jshint.version}</echo>
+ <echo>${jshint.results}</echo>
+ <echo></echo>
</then>
</if>
- <!-- Clear property for next run: -->
- <var name="node.jslint.response" unset="true"/>
</then>
<else>
- <echo>Using Rhino. Install nodejs to improve jslint speed, or skip with -Dlint.skip=true</echo>
- <!--
- Need to find a way to convert fileset to args (script?) to
- avoid ' ', which will break for files with ' in them
-
- Evaluates to the following java execution line...
- java -r js.jar jslintconsole.js 'file1.js' 'file2.js' 'file3.js'
- -->
-
- <java jar="${rhino.jar}" fork="true" failonerror="${jslint.failonerror}">
- <arg file="${jslintconsole.js}" />
- <arg value="${jslintsrc.js}" />
- <arg line="'${jsfileargs}'" />
- </java>
+ <if>
+ <or>
+ <istrue value="${node.online}"/>
+ <http url="${node.jslint.url}"/>
+ </or>
+ <then>
+ <property name="node.online" value="true"/>
+ <post to="${node.jslint.url}" property="node.jslint.response" failonerror="${lint.failonerror}" verbose="false">
+ <prop name="files" value="${jsfileargs}"/>
+ <prop name="failonerror" value="${lint.failonerror}"/>
+ </post>
+ <!-- Since Ant doesn't really failonerror for the post task,
+ handle this ourselves: -->
+ <if>
+ <not>
+ <isset property="node.jslint.response"/>
+ </not>
+ <then>
+ <fail>JSLint failed. To view lint output and continue the build, run ant with -Dlint.failonerror=false.</fail>
+ </then>
+ <else>
+ <echo>${node.jslint.response}</echo>
+ </else>
+ </if>
+ <!-- Clear property for next run: -->
+ <var name="node.jslint.response" unset="true"/>
+ </then>
+ <else>
+ <echo>Using Rhino. Install nodejs to improve jslint speed, or skip with -Dlint.skip=true</echo>
+ <!--
+ Need to find a way to convert fileset to args (script?) to
+ avoid ' ', which will break for files with ' in them
+
+ Evaluates to the following java execution line...
+ java -r js.jar jslintconsole.js 'file1.js' 'file2.js' 'file3.js'
+ -->
+
+ <java jar="${rhino.jar}" fork="true" failonerror="${jslint.failonerror}">
+ <arg file="${jslintconsole.js}" />
+ <arg value="${jslintsrc.js}" />
+ <arg line="'${jsfileargs}'" />
+ </java>
+ </else>
+ </if>
</else>
</if>
</sequential>
</macrodef>
<macrodef name="registerversion">
<attribute name="module" />
<attribute name="classname" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/versioncode.txt" property="@{module}-@{classname}-version" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
<token key="CLASSNAME" value="@{classname}"/>
</replacetokens>
</filterchain>
</loadfile>
- <echo level="info">Adding Version Registration Code to @{file}</echo>
+ <echo level="verbose">Adding Version Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}-@{classname}-version}</concat>
</sequential>
</macrodef>
<macrodef name="addlang">
<attribute name="dir" />
<attribute name="module" />
<attribute name="dest" />
<attribute name="lang" default="" />
<attribute name="details" default = ""/>
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}@{lang}_details" value="" />
</then>
<else>
<property name="@{module}@{lang}_details" value=",@{details}" />
</else>
</if>
<if>
<equals arg1="@{lang}" arg2="" />
<then>
<property name="@{module}@{lang}_fullname" value="@{module}" />
</then>
<else>
<property name="@{module}@{lang}_fullname" value="@{module}_@{lang}" />
</else>
</if>
<if>
<available file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<then>
<mkdir dir="${component.langbuilddir}" />
<java jar="${rhino.jar}" fork="true" failonerror="true">
<jvmarg value="-Dfile.encoding=utf-8" />
<arg file="${yrb2jsonconsole.js}" />
<arg file="${yrb2jsonsrc.js}" />
<arg file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<arg file="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" />
</java>
- <echo level="info">Wrapping ${component.langbuilddir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
+ <echo level="verbose">Wrapping ${component.langbuilddir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</then>
<else>
- <echo level="info">Wrapping @{dir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
+ <echo level="verbose">Wrapping @{dir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="@{dir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</else>
</if>
<copy file="${builddir}/files/langtemplate.txt" tofile="@{dest}/${@{module}@{lang}_fullname}.js" overwrite="true" outputencoding="utf-8">
<filterset>
<filter token="LANG" value="@{lang}" />
<filter token="LANG_MODULE" value="lang/${@{module}@{lang}_fullname}" />
<filter token="STRINGS" value="${@{module}@{lang}-strs-loaded}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="LANG_DETAILS" value="${@{module}@{lang}_details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addmodule">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
- <echo level="info">Wrapping @{file} in YUI.add module</echo>
+ <echo level="verbose">Wrapping @{file} in YUI.add module</echo>
<copy file="${builddir}/files/moduletemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="DETAILS" value="${@{module}-details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addrollup">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
- <echo level="info">Adding Rollup @{file} using YUI.add</echo>
+ <echo level="verbose">Adding Rollup @{file} using YUI.add</echo>
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}"/>
<filter token="DETAILS" value="${@{module}-details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addlangrollup">
<attribute name="module" />
<attribute name="dir" />
<sequential>
- <echo level="info">Registering rollup info for lang files in @{dir} using YUI.add</echo>
+ <echo level="verbose">Registering rollup info for lang files in @{dir} using YUI.add</echo>
<for list="${component.rollup.lang}" param="lang" trim="true">
<sequential>
<loadfile srcfile="@{dir}/@{module}_@{lang}.js" property="@{module}-@{lang}-code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}_@{lang}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}-@{lang}-details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}_@{lang}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{lang}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}_@{lang}"/>
<filter token="DETAILS" value=", ${@{module}-@{lang}-details}"/>
</filterset>
</copy>
</sequential>
</for>
<loadfile srcfile="@{dir}/@{module}.js" property="@{module}--code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}--details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}--code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}"/>
<filter token="DETAILS" value=", ${@{module}--details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="stampcss">
<attribute name="module" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/css-stamp.txt" property="@{module}" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
</replacetokens>
</filterchain>
</loadfile>
- <echo level="info">Adding CSS Registration Code to @{file}</echo>
+ <echo level="verbose">Adding CSS Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}}</concat>
</sequential>
</macrodef>
</project>
diff --git a/componentbuild/shared/targets.xml b/componentbuild/shared/targets.xml
index ee54c77..fc0f03a 100644
--- a/componentbuild/shared/targets.xml
+++ b/componentbuild/shared/targets.xml
@@ -1,202 +1,226 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiSharedTargets">
<echo level="info">Starting Build For ${component}</echo>
- <echo level="info">Ant Properties</echo>
- <echo level="info"> Home : ${ant.home}</echo>
- <echo level="info"> Ant Version : ${ant.version}</echo>
- <echo level="info"> Build File : ${ant.file}</echo>
- <echo level="info">Local Build Properties</echo>
- <echo level="info"> version : ${yui.version}</echo>
- <echo level="info"> srcdir : ${srcdir}</echo>
- <echo level="info"> builddir : ${builddir}</echo>
- <echo level="info"> component : ${component}</echo>
- <echo level="info"> component.basefilename : ${component.basefilename}</echo>
- <echo level="info"> component.basedir : ${component.basedir}</echo>
- <echo level="info"> component.builddir : ${component.builddir}</echo>
- <echo level="info">Global Build Properties</echo>
- <echo level="info"> global.build.base : ${global.build.base}</echo>
- <echo level="info"> global.build.component : ${global.build.component}</echo>
- <echo level="info"> global.build.component.assets : ${global.build.component.assets}</echo>
+ <echo level="verbose">Ant Properties</echo>
+ <echo level="verbose"> Home : ${ant.home}</echo>
+ <echo level="verbose"> Ant Version : ${ant.version}</echo>
+ <echo level="verbose"> Build File : ${ant.file}</echo>
+ <echo level="verbose">Local Build Properties</echo>
+ <echo level="verbose"> version : ${yui.version}</echo>
+ <echo level="verbose"> srcdir : ${srcdir}</echo>
+ <echo level="verbose"> builddir : ${builddir}</echo>
+ <echo level="verbose"> component : ${component}</echo>
+ <echo level="verbose"> component.basefilename : ${component.basefilename}</echo>
+ <echo level="verbose"> component.basedir : ${component.basedir}</echo>
+ <echo level="verbose"> component.builddir : ${component.builddir}</echo>
+ <echo level="verbose">Global Build Properties</echo>
+ <echo level="verbose"> global.build.base : ${global.build.base}</echo>
+ <echo level="verbose"> global.build.component : ${global.build.component}</echo>
+ <echo level="verbose"> global.build.component.assets : ${global.build.component.assets}</echo>
<dirname property="targets.basedir" file="${ant.file.YuiSharedTargets}"/>
<import file="${targets.basedir}/macrolib.xml" description="Macrodef definitions - jslint, yuicompessor, registerversion" />
<target name="all" depends="local, deploy" description="Build and Deploy to Global Build Directory" />
<target name="local" depends="clean, init, build, minify, lint" description="Build and Deploy to Local Build Directory" />
<target name="init">
<tstamp/>
<mkdir dir="${component.builddir}" />
<createdetails />
<antcall target="-lint-server"/>
</target>
<target name="-lint-server" description="Start JSLint Server" unless="lint.skip">
<antcall target="-node">
<param name="src" value="${builddir}/lib/jslint/jslint-node.js"/>
</antcall>
</target>
<target name="-node" description="Start NodeJS Server" unless="node.spawn">
<if>
<not>
<http url="${node.jslint.url}"/>
</not>
<then>
<!-- You can't set failifexecutionfails if spawn is true. Argh. -->
<!-- Check if it's installed first. -->
<exec resultproperty="node.status" executable="node" failonerror="false" failifexecutionfails="false" searchpath="true" resolveexecutable="true">
<arg value="-v"/>
</exec>
<if>
<equals arg1="${node.status}" arg2="0"/>
<then>
<echo level="info">Spawning Node.js app at: ${src}</echo>
<exec executable="node" spawn="true" failonerror="false" searchpath="true" resolveexecutable="true">
<arg value="${src}"/>
</exec>
</then>
<else>
<echo level="info">For faster builds, install Node.js.</echo>
</else>
</if>
<!-- Don't fail if node doesn't exist, fails to start, etc.
We will fallback to the slow Rhino engine later. -->
</then>
</if>
<!-- Don't try to start again. -->
<property name="node.spawn" value="true"/>
</target>
<target name="clean" description="Clean Local Build Directory" unless="clean.skip">
<delete dir="${component.builddir}" />
</target>
<target name="build" />
<!-- MIN -->
<target name="minify" description="Create component-min.js from component.js">
<yuicompress src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-min.js" args="${yuicompressor.js.args.internal}" />
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<for param="file">
<path>
<fileset dir="${component.builddir}/lang" includes="*.js"/>
</path>
<sequential>
<yuicompress src="@{file}" dest="@{file}" args="${yuicompressor.js.args.internal}" />
</sequential>
</for>
</then>
</if>
</target>
<target name="lint" description="Run jslint over the local build files (default settings)" unless="lint.skip">
- <jslint>
- <jsfiles>
- <fileset dir="${component.builddir}" includes="*.js" />
- </jsfiles>
- </jslint>
+ <if>
+ <istrue value="${lint.all}" />
+ <then>
+ <!-- Lint all files -->
+ <jslint>
+ <jsfiles>
+ <fileset dir="${component.builddir}" includes="*.js" />
+ </jsfiles>
+ </jslint>
+ </then>
+ <else>
+ <!-- Only lint raw files -->
+ <jslint>
+ <jsfiles>
+ <fileset dir="${component.builddir}" includes="*.js">
+ <none>
+ <filename name="*-debug.js"/>
+ <filename name="*-min.js"/>
+ </none>
+ </fileset>
+ </jsfiles>
+ </jslint>
+ </else>
+ </if>
</target>
<!-- DEPLOY -->
<target name="deploy" description="Copy files to global location" depends="deploybuild, deployassets, deployskins, deploylang, deploydocs"></target>
<target name="deploybuild" description="Copy built files to global build location">
- <copy todir="${global.build.component}" overwrite="true" verbose="true">
+ <copy todir="${global.build.component}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}" includes="*.js" />
</copy>
</target>
<target name="deployassets" if="component.assets.exist">
- <copy todir="${global.build.component.assets}" flatten="${component.assets.flatten}" overwrite="true" verbose="true">
+ <copy todir="${global.build.component.assets}" flatten="${component.assets.flatten}" overwrite="true" verbose="false">
<fileset dir="${component.assets.base}" includes="${component.assets.files}" excludes="skins/, legacy/" />
</copy>
- <copy todir="${global.build.component.assets}" flatten="${component.assets.legacy.flatten}" preservelastmodified="true" failonerror="false" verbose="true">
+ <copy todir="${global.build.component.assets}" flatten="${component.assets.legacy.flatten}" preservelastmodified="true" failonerror="false" verbose="false">
<fileset dir="${component.assets.legacy.base}" includes="${component.assets.legacy.files}" excludes="skins/" />
</copy>
</target>
<target name="deployskins" if="skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
- <echo level="info">Deploying Skin files for @{skin.dir} :: ${skin.name}</echo>
- <copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="true">
+ <echo level="verbose">Deploying Skin files for @{skin.dir} :: ${skin.name}</echo>
+ <copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" />
</copy>
- <copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="true">
+ <copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="false">
<fileset dir="${component.assets.skins.base}/${skin.name}" includes="${component.assets.skins.files}" />
</copy>
<var name="skin.name" unset="true" />
</sequential>
</for>
</target>
<target name="deploylang" description="Copy language bundles to global build location">
- <copy todir="${global.build.component}/lang" overwrite="true" failonerror="false" verbose="true">
- <fileset dir="${component.builddir}/lang" includes="*.js" />
- </copy>
+ <if>
+ <available file="${component.builddir}/lang" type="dir" />
+ <then>
+ <copy todir="${global.build.component}/lang" overwrite="true" failonerror="false">
+ <fileset dir="${component.builddir}/lang" includes="*.js" />
+ </copy>
+ </then>
+ </if>
</target>
<target name="deploydocs" description="Copy doc files to global doc locations">
<!-- TODO -->
</target>
<target name="-prepend" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true">
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true" append="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<move file="${workingdir}/${component.basefilename}.js.tmp" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-append" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
</target>
<target name="-prependdebug" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}-debug.js.tmp" fixlastline="true" >
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
<move file="${workingdir}/${component.basefilename}-debug.js.tmp" tofile="${component.builddir}/${component.basefilename}-debug.js" />
</target>
<target name="-appenddebug" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}-debug.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
</concat>
</target>
</project>
|
yui/builder
|
ae231557e58e4a0a25c2f84758278876db975868
|
Minor updates to Node JSLint processor so that it logs better
|
diff --git a/componentbuild/lib/jslint/jslint-node.js b/componentbuild/lib/jslint/jslint-node.js
index e028f14..8516c2b 100644
--- a/componentbuild/lib/jslint/jslint-node.js
+++ b/componentbuild/lib/jslint/jslint-node.js
@@ -1,119 +1,127 @@
/**
* Javascript Shell Script to Load and JSLint js files through Rhino Javascript Shell
* The jslint source file is expected as the first argument, followed by the list of JS files to JSLint
*
* e.g.
* java -j js.jar /tools/fulljslint.js testFile1.js testFile2.js testFile3.js
**/
JSLINT = require("./fulljslint").JSLINT;
(function(){ // Just to keep stuff seperate from JSLINT code
var PORT = parseInt(process.argv[2]) || 8081;
var OPTS = {
browser : true,
//laxLineEnd : true,
undef: true,
newcap: false,
predef:["YUI", "window", "YUI_config", "YAHOO", "YAHOO_config", "Event",
- "opera", "exports", "document", "navigator", "console", "self"]
+ "opera", "exports", "document", "navigator", "console", "self", "require",
+ "module", "process", "__dirname", "__filename"]
};
- function test(js) {
+ function test(js, file) {
var body = "", code = 200;
var success = JSLINT(js, OPTS);
if (success) {
- return "OK";
+ return {
+ "content": '\t[OK] ' + file,
+ code: code
+ };
} else {
- for (var i=0; i < JSLINT.errors.length; ++i) {
- var e = JSLINT.errors[i];
- if (e) {
- body += ("\t" + e.line + ", " + e.character + ": " + e.reason + "\n\t" + clean(e.evidence) + "\n");
+ if (JSLINT.errors.length) {
+ body += '[JSLINT] ' + file + '\n';
+ body += '----------------------------------------------------------\n';
+ for (var i=0; i < JSLINT.errors.length; ++i) {
+ var e = JSLINT.errors[i];
+ if (e) {
+ body += ("\t" + e.line + ", " + e.character + ": " + e.reason + "\n\t" + clean(e.evidence) + "\n");
+ }
}
+ body += '----------------------------------------------------------\n';
}
- body += "\n";
// Last item is null if JSLint hit a fatal error
if (JSLINT.errors && JSLINT.errors[JSLINT.errors.length-1] === null) {
code = 500;
}
return {
"content" : body,
"code" : code
};
}
}
function clean(str) {
var trimmed = "";
if (str) {
if(str.length <= 500) {
trimmed = str.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
} else {
trimmed = "[Code Evidence Omitted: Greater than 500 chars]";
}
}
return trimmed;
}
var qs = require("querystring");
var fs = require("fs");
var EventEmitter = require("events").EventEmitter;
var ticket = 0;
require("http").createServer(function (req, res) {
var data = "";
req.addListener("data", function (chunk) {
data += chunk;
});
var proc = new EventEmitter();
proc.addListener("end", function (code, body, die) {
res.writeHead(code, {"Content-type" : "text/plain"});
res.end(body);
if (die) process.exit(0);
});
req.addListener("end", function () {
ticket++;
var code = 200, body;
var die = "/kill" === req.url;
if (die) body = "Goodbye.";
else if (req.method === "POST") {
var query = qs.parse(data);
var files = query["files"].split("' '");
var failOnError = query["failonerror"] == "true";
var results = [];
files.forEach(function (file) {
fs.readFile(file, function (err, data) {
- var diagnosis = test(data.toString("utf8"));
+ var diagnosis = test(data.toString("utf8"), file);
results.push(diagnosis.content);
code = (
failOnError &&
diagnosis.code !== 200
) ? diagnosis.code : code;
if (results.length == files.length) proc.emit("end", code, results.join("\n"));
});
});
} else {
body = "Ready.";
}
if (body) proc.emit("end", code, body, die);
});
}).listen(PORT, "127.0.0.1");
require("sys").puts("Server started on port " + PORT);
(function () {
var reap;
setInterval(function () {
if (reap == ticket) process.exit(0);
reap = ticket;
}, 10000);
})();
})();
|
yui/builder
|
f0ad10d20d5d8f5efb367bcc2b0651bc41d5ad04
|
Changed the verbosity of the echo statements to verbose instead of info
|
diff --git a/componentbuild/3.x/module.xml b/componentbuild/3.x/module.xml
index 4562dc8..525d566 100644
--- a/componentbuild/3.x/module.xml
+++ b/componentbuild/3.x/module.xml
@@ -1,172 +1,172 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiModuleTargets">
<dirname property="module.basedir" file="${ant.file.YuiModuleTargets}"/>
<import file="${module.basedir}/../shared/targets.xml" description="Targets common to Rollup/Module" />
<target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs" />
<target name="buildskins" depends="-buildskins, -rollupcss" />
<target name="buildlangs" depends="-buildlangs, -rolluplangs" />
<!-- CORE -->
<target name="buildcore" depends="builddebug, -createcore, -loggerregex" description="Create component.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}.js" eol="${buildfiles.eol}" />
</target>
<target name="-createcore">
<copy file="${component.builddir}/${component.basefilename}-debug.js" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-loggerregex" description="Replace logger statements" unless="component.logger.regex.skip">
- <echo level="info">Replacing Logger Statements in ${component.builddir}/${component.basefilename}.js</echo>
+ <echo level="verbose">Replacing Logger Statements in ${component.builddir}/${component.basefilename}.js</echo>
<replaceregexp file="${component.builddir}/${component.basefilename}.js"
byline="${component.logger.regex.byline}"
match="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</target>
<!-- DEBUG -->
<target name="builddebug" depends="-concatdebug, -registerdebug, -prependdebug, -appenddebug" description="Create component-debug.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}-debug.js" eol="${buildfiles.eol}" />
</target>
<target name="-concatdebug">
<concatsource destfile="${component.builddir}/${component.basefilename}-debug.js" sourcedir="${component.jsfiles.base}" sourcefiles="${component.jsfiles}" />
</target>
<target name="-registerdebug" unless="register.skip">
<addmodule module="${component.module}" file="${component.builddir}/${component.basefilename}-debug.js" details="${component.details.hash}" />
</target>
<target name="-rollupjs" if="rollup">
<if>
<isset property="rollup.sub"/>
<then>
- <echo level="info">Module: Build a rollup of a rollup; moving rollup.sub properties into rollup properties.</echo>
+ <echo level="verbose">Module: Build a rollup of a rollup; moving rollup.sub properties into rollup properties.</echo>
<var name="rollup.builddir" unset="true"/>
<var name="rollup.component" unset="true"/>
<var name="rollup.component.basefilename" unset="true"/>
<propertycopy name="rollup.builddir" from="rollup.sub.builddir"/>
<propertycopy name="rollup.component" from="rollup.sub.component"/>
<propertycopy name="rollup.component.basefilename" from="rollup.sub.component.basefilename"/>
</then>
</if>
- <echo level="info">Module: Rolling up ${component.basefilename}-debug.js into ${rollup.component.basefilename}-debug.js</echo>
+ <echo level="verbose">Module: Rolling up ${component.basefilename}-debug.js into ${rollup.component.basefilename}-debug.js</echo>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}-debug.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
</target>
<!-- SKINS -->
<target name="-buildskins" depends="-concatskins" description="Create skin rollup in local component build directory" if="component.skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
- <echo level="info">Fixing CRLF for Skin files for @{skin.dir} :: ${skin.name}</echo>
+ <echo level="verbose">Fixing CRLF for Skin files for @{skin.dir} :: ${skin.name}</echo>
<fixcrlf srcdir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" eol="${buildfiles.eol}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--fixcrlf srcdir="${component.builddir}/assets/skins/sam" includes="${component}.css" eol="${buildfiles.eol}" /-->
</target>
<target name="-buildlangs" description="Create language packs in the local component build directory" if="component.langs.exist">
<mkdir dir="${component.builddir}/lang" />
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<addlang dir="${component.lang.base}" module="${component}" lang="@{lang}" dest="${component.builddir}/lang" />
</sequential>
</for>
<addlang dir="${component.lang.base}" module="${component}" lang="" dest="${component.builddir}/lang/" />
</target>
<target name="-rolluplangs" if="rolluplangs">
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<concat destfile="${rollup.builddir}/lang/${rollup.component}_@{lang}.js" append="true" fixlastline="true">
<fileset dir="${component.builddir}/lang" includes="*_@{lang}.js" />
</concat>
</sequential>
</for>
<concat destfile="${rollup.builddir}/lang/${rollup.component}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}/lang" files="${component}.js" />
</concat>
</target>
<target name="-concatskins" if="component.skins.exist">
- <echo level="info">Concating Skins</echo>
+ <echo level="verbose">Concating Skins</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
- <echo level="info">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
+ <echo level="verbose">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concatsource destfile="${component.builddir}/assets/skins/${skin.name}/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/${skin.name}/${component}-skin.css" />
<!-- Stamp Skin CSS -->
<stampcss file="${component.builddir}/assets/skins/${skin.name}/${component}.css" module="skin-${skin.name}-${component}" />
<yuicompress type="css" src="${component.builddir}/assets/skins/${skin.name}/${component}.css" dest="${component.builddir}/assets/skins/${skin.name}/${component}.css" args="${yuicompressor.css.args.internal}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concatsource destfile="${component.builddir}/assets/skins/sam/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/sam/${component}-skin.css" />
<yuicompress type="css" src="${component.builddir}/assets/skins/sam/${component}.css" dest="${component.builddir}/assets/skins/sam/${component}.css" args="${yuicompressor.css.args.internal}" /-->
</target>
<target name="-rollupcss" if="rollupskins">
- <echo level="info">Rolling up ${component}.css into ${rollup.component}.css</echo>
+ <echo level="verbose">Rolling up ${component}.css into ${rollup.component}.css</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
- <echo level="info">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
+ <echo level="verbose">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concat destfile="${rollup.builddir}/assets/skins/${skin.name}/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/${skin.name}" files="${component}.css" />
</concat>
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concat destfile="${rollup.builddir}/assets/skins/sam/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/sam" files="${component}.css" />
</concat-->
</target>
<!-- Tests -->
<target name="tests" depends="-lint-server">
<echo level="info">Generating test module for ${component}</echo>
<echo level="info"> Test module: ${tests.component}</echo>
<echo level="info"> Test module source directory: ${tests.srcdir}</echo>
<echo level="info"> Test module source files: ${tests.jsfiles}</echo>
<echo level="info"> Test module output directory: ${tests.builddir}</echo>
<echo level="info"> Test module file: ${tests.builddir}/${tests.component}.js</echo>
<echo level="info"> </echo>
<available file="${tests.srcdir}" type="dir" property="tests.srcdir.exists"/>
<var name="buildfile" value="${tests.builddir}/${tests.component}.js"/>
<arrayliteral from="tests.requires" to="tests.details.requires" key="requires"/>
<concatsource destfile="${buildfile}" sourcedir="${tests.srcdir}" sourcefiles="${tests.jsfiles}"/>
<addmodule file="${buildfile}" module="${tests.component}" details="{${tests.details.requires}}"/>
<jslint>
<jsfiles>
<fileset file="${buildfile}"/>
</jsfiles>
</jslint>
<echo level="info">Test module ${tests.component} created</echo>
</target>
</project>
|
yui/builder
|
e1b5751d4f8fb61a9f0fa49030cab5b8f548ffc3
|
Added CSS stamping for Loader detection
|
diff --git a/componentbuild/3.x/module.xml b/componentbuild/3.x/module.xml
index 4e0c92f..4562dc8 100644
--- a/componentbuild/3.x/module.xml
+++ b/componentbuild/3.x/module.xml
@@ -1,170 +1,172 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiModuleTargets">
<dirname property="module.basedir" file="${ant.file.YuiModuleTargets}"/>
<import file="${module.basedir}/../shared/targets.xml" description="Targets common to Rollup/Module" />
<target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs" />
<target name="buildskins" depends="-buildskins, -rollupcss" />
<target name="buildlangs" depends="-buildlangs, -rolluplangs" />
<!-- CORE -->
<target name="buildcore" depends="builddebug, -createcore, -loggerregex" description="Create component.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}.js" eol="${buildfiles.eol}" />
</target>
<target name="-createcore">
<copy file="${component.builddir}/${component.basefilename}-debug.js" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-loggerregex" description="Replace logger statements" unless="component.logger.regex.skip">
<echo level="info">Replacing Logger Statements in ${component.builddir}/${component.basefilename}.js</echo>
<replaceregexp file="${component.builddir}/${component.basefilename}.js"
byline="${component.logger.regex.byline}"
match="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</target>
<!-- DEBUG -->
<target name="builddebug" depends="-concatdebug, -registerdebug, -prependdebug, -appenddebug" description="Create component-debug.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}-debug.js" eol="${buildfiles.eol}" />
</target>
<target name="-concatdebug">
<concatsource destfile="${component.builddir}/${component.basefilename}-debug.js" sourcedir="${component.jsfiles.base}" sourcefiles="${component.jsfiles}" />
</target>
<target name="-registerdebug" unless="register.skip">
<addmodule module="${component.module}" file="${component.builddir}/${component.basefilename}-debug.js" details="${component.details.hash}" />
</target>
<target name="-rollupjs" if="rollup">
<if>
<isset property="rollup.sub"/>
<then>
<echo level="info">Module: Build a rollup of a rollup; moving rollup.sub properties into rollup properties.</echo>
<var name="rollup.builddir" unset="true"/>
<var name="rollup.component" unset="true"/>
<var name="rollup.component.basefilename" unset="true"/>
<propertycopy name="rollup.builddir" from="rollup.sub.builddir"/>
<propertycopy name="rollup.component" from="rollup.sub.component"/>
<propertycopy name="rollup.component.basefilename" from="rollup.sub.component.basefilename"/>
</then>
</if>
<echo level="info">Module: Rolling up ${component.basefilename}-debug.js into ${rollup.component.basefilename}-debug.js</echo>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}-debug.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
</target>
<!-- SKINS -->
<target name="-buildskins" depends="-concatskins" description="Create skin rollup in local component build directory" if="component.skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Fixing CRLF for Skin files for @{skin.dir} :: ${skin.name}</echo>
<fixcrlf srcdir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" eol="${buildfiles.eol}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--fixcrlf srcdir="${component.builddir}/assets/skins/sam" includes="${component}.css" eol="${buildfiles.eol}" /-->
</target>
<target name="-buildlangs" description="Create language packs in the local component build directory" if="component.langs.exist">
<mkdir dir="${component.builddir}/lang" />
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<addlang dir="${component.lang.base}" module="${component}" lang="@{lang}" dest="${component.builddir}/lang" />
</sequential>
</for>
<addlang dir="${component.lang.base}" module="${component}" lang="" dest="${component.builddir}/lang/" />
</target>
<target name="-rolluplangs" if="rolluplangs">
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<concat destfile="${rollup.builddir}/lang/${rollup.component}_@{lang}.js" append="true" fixlastline="true">
<fileset dir="${component.builddir}/lang" includes="*_@{lang}.js" />
</concat>
</sequential>
</for>
<concat destfile="${rollup.builddir}/lang/${rollup.component}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}/lang" files="${component}.js" />
</concat>
</target>
<target name="-concatskins" if="component.skins.exist">
<echo level="info">Concating Skins</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concatsource destfile="${component.builddir}/assets/skins/${skin.name}/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/${skin.name}/${component}-skin.css" />
+ <!-- Stamp Skin CSS -->
+ <stampcss file="${component.builddir}/assets/skins/${skin.name}/${component}.css" module="skin-${skin.name}-${component}" />
<yuicompress type="css" src="${component.builddir}/assets/skins/${skin.name}/${component}.css" dest="${component.builddir}/assets/skins/${skin.name}/${component}.css" args="${yuicompressor.css.args.internal}" />
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concatsource destfile="${component.builddir}/assets/skins/sam/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/sam/${component}-skin.css" />
<yuicompress type="css" src="${component.builddir}/assets/skins/sam/${component}.css" dest="${component.builddir}/assets/skins/sam/${component}.css" args="${yuicompressor.css.args.internal}" /-->
</target>
<target name="-rollupcss" if="rollupskins">
<echo level="info">Rolling up ${component}.css into ${rollup.component}.css</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concat destfile="${rollup.builddir}/assets/skins/${skin.name}/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/${skin.name}" files="${component}.css" />
</concat>
<var name="skin.name" unset="true" />
</sequential>
</for>
<!--concat destfile="${rollup.builddir}/assets/skins/sam/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/sam" files="${component}.css" />
</concat-->
</target>
<!-- Tests -->
<target name="tests" depends="-lint-server">
<echo level="info">Generating test module for ${component}</echo>
<echo level="info"> Test module: ${tests.component}</echo>
<echo level="info"> Test module source directory: ${tests.srcdir}</echo>
<echo level="info"> Test module source files: ${tests.jsfiles}</echo>
<echo level="info"> Test module output directory: ${tests.builddir}</echo>
<echo level="info"> Test module file: ${tests.builddir}/${tests.component}.js</echo>
<echo level="info"> </echo>
<available file="${tests.srcdir}" type="dir" property="tests.srcdir.exists"/>
<var name="buildfile" value="${tests.builddir}/${tests.component}.js"/>
<arrayliteral from="tests.requires" to="tests.details.requires" key="requires"/>
<concatsource destfile="${buildfile}" sourcedir="${tests.srcdir}" sourcefiles="${tests.jsfiles}"/>
<addmodule file="${buildfile}" module="${tests.component}" details="{${tests.details.requires}}"/>
<jslint>
<jsfiles>
<fileset file="${buildfile}"/>
</jsfiles>
</jslint>
<echo level="info">Test module ${tests.component} created</echo>
</target>
</project>
diff --git a/componentbuild/files/css-stamp.txt b/componentbuild/files/css-stamp.txt
new file mode 100644
index 0000000..8d13214
--- /dev/null
+++ b/componentbuild/files/css-stamp.txt
@@ -0,0 +1,2 @@
+/* YUI CSS Detection Stamp */
+#yui3-css-stamp.@MODULE@ { display: none; }
diff --git a/componentbuild/shared/cssmodule.xml b/componentbuild/shared/cssmodule.xml
index dfa6e50..0add062 100644
--- a/componentbuild/shared/cssmodule.xml
+++ b/componentbuild/shared/cssmodule.xml
@@ -1,27 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiCssModuleTargets">
<dirname property="cssmodule.basedir" file="${ant.file.YuiCssModuleTargets}"/>
<import file="${cssmodule.basedir}/../shared/targets.xml" description="Targets common to Rollup/Module" />
<target name="build" depends="buildcore" />
<target name="buildcore">
<concatsource destfile="${component.builddir}/${component.basefilename}.css" sourcedir="${component.cssfiles.base}" sourcefiles="${component.cssfiles}" />
+ <stampcss file="${component.builddir}/${component.basefilename}.css" module="${component}" />
</target>
<target name="minify">
<yuicompress type="css" src="${component.builddir}/${component.basefilename}.css" dest="${component.builddir}/${component.basefilename}-min.css" args="${yuicompressor.css.args.internal}" />
</target>
<target name="lint">
<!-- TODO : CSS Lint support. Currently need to add @charset "UTF-8";-->
</target>
<target name="deploybuild" description="Copy built files to global build location">
<copy todir="${global.build.component}" preservelastmodified="true">
<fileset dir="${component.builddir}" includes="*.css" />
</copy>
</target>
</project>
diff --git a/componentbuild/shared/macrolib.xml b/componentbuild/shared/macrolib.xml
index b7f6721..a06c6c9 100644
--- a/componentbuild/shared/macrolib.xml
+++ b/componentbuild/shared/macrolib.xml
@@ -1,384 +1,400 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiMacroLib">
<macrodef name="arrayliteral">
<attribute name="from" />
<attribute name="to" />
<attribute name="key" />
<sequential>
<if>
<and>
<isset property="@{from}" />
<length string="${@{from}}" when="ne" length="0" />
</and>
<then>
<propertyregex property="array"
override="true"
input="${@{from}}"
casesensitive="false"
regexp="([^\,\s]+)"
replace="'\1'"
/>
<property name="@{to}" value="@{key}:[${array}]" />
</then>
</if>
</sequential>
</macrodef>
<macrodef name="createdetails">
<sequential>
<arrayliteral from="component.use" to="component.details.use" key="use" />
<arrayliteral from="component.supersedes" to="component.details.supersedes" key="supersedes" />
<arrayliteral from="component.requires" to="component.details.requires" key="requires" />
<arrayliteral from="component.optional" to="component.details.optional" key="optional" />
<arrayliteral from="component.after" to="component.details.after" key="after" />
<arrayliteral from="component.lang" to="component.details.lang" key="lang" />
<if>
<isset property="component.skinnable" />
<then>
<property name="component.details.skinnable" value="skinnable:${component.skinnable}" />
</then>
</if>
<propertyselector property="details.list"
delimiter=","
match="component\.details.([^\.]*)"
select="\1"
casesensitive="false" />
<var name="details" value="" />
<if>
<isset property="details.list" />
<then>
<for list="${details.list}" param="val">
<sequential>
<var name="details" value="${component.details.@{val}}, ${details}" />
</sequential>
</for>
<propertyregex property="component.details.hash"
input="{${details}}"
regexp="(\,\s*?\})"
replace="}"
casesensitive="false" />
</then>
<else>
<property name="component.details.hash" value="" />
</else>
</if>
</sequential>
</macrodef>
<if>
<!-- The yui2 builder-integration script embeds macrolib.xml
by itself for other macros, which leaves yuicompressor.jar
unset. If that's the case, don't define the compressor tasks. -->
<isset property="yuicompressor.jar"/>
<then>
<taskdef name="yuicompressor"
classname="com.yahoo.platform.yui.compressor.CompressorTask"
classpath="${yuicompressor.jar}"/>
<!-- Maps the legacy yuicompress task into a yuicompressor task. -->
<macrodef name="yuicompress">
<attribute name="src" />
<attribute name="dest" />
<attribute name="args" />
<!-- Unused. Type is detected automatically from the @{src} filename. -->
<attribute name="type" default="?"/>
<!-- If you had to override this, use the type option in args instead. -->
<sequential>
<yuicompressor input="@{src}" output="@{dest}" options="@{args}"/>
</sequential>
</macrodef>
</then>
</if>
<macrodef name="concatsource">
<attribute name="destfile" />
<attribute name="sourcedir" />
<attribute name="sourcefiles" />
<attribute name="workingdir" default="${workingdir}" />
<element name="filters" optional="true" description="Additonal filters to apply to individual files"/>
<sequential>
<echo level="info">Concatenating</echo>
<echo level="info"> Source Files : @{sourcefiles}</echo>
<echo level="info"> In Source Dir : @{sourcedir}</echo>
<echo level="info"> To : @{destfile}</echo>
<delete dir="@{workingdir}" quiet="true"/>
<copy todir="@{workingdir}">
<filelist dir="@{sourcedir}" files="@{sourcefiles}" />
<filterchain>
<filters />
<fixcrlf fixlast="true" eof="remove"/>
</filterchain>
</copy>
<concat destfile="@{destfile}" fixlastline="true">
<filelist dir="@{workingdir}" files="@{sourcefiles}" />
</concat>
<delete dir="${workingdir}" quiet="true" />
</sequential>
</macrodef>
<macrodef name="jslint">
<element name="jsfiles" optional="false" />
<sequential>
<pathconvert pathsep="' '" property="jsfileargs">
<jsfiles />
</pathconvert>
<if>
<or>
<istrue value="${node.online}"/>
<http url="${node.jslint.url}"/>
</or>
<then>
<property name="node.online" value="true"/>
<post to="${node.jslint.url}" property="node.jslint.response" failonerror="${lint.failonerror}">
<prop name="files" value="${jsfileargs}"/>
<prop name="failonerror" value="${lint.failonerror}"/>
</post>
<!-- Since Ant doesn't really failonerror for the post task,
handle this ourselves: -->
<if>
<not>
<isset property="node.jslint.response"/>
</not>
<then>
<fail>JSLint failed. To view lint output and continue the build, run ant with -Dlint.failonerror=false.</fail>
</then>
</if>
<!-- Clear property for next run: -->
<var name="node.jslint.response" unset="true"/>
</then>
<else>
<echo>Using Rhino. Install nodejs to improve jslint speed, or skip with -Dlint.skip=true</echo>
<!--
Need to find a way to convert fileset to args (script?) to
avoid ' ', which will break for files with ' in them
Evaluates to the following java execution line...
java -r js.jar jslintconsole.js 'file1.js' 'file2.js' 'file3.js'
-->
<java jar="${rhino.jar}" fork="true" failonerror="${jslint.failonerror}">
<arg file="${jslintconsole.js}" />
<arg value="${jslintsrc.js}" />
<arg line="'${jsfileargs}'" />
</java>
</else>
</if>
</sequential>
</macrodef>
<macrodef name="registerversion">
<attribute name="module" />
<attribute name="classname" />
<attribute name="file" />
<sequential>
<loadfile srcfile="${builddir}/files/versioncode.txt" property="@{module}-@{classname}-version" >
<filterchain>
<replacetokens>
<token key="MODULE" value="@{module}"/>
<token key="CLASSNAME" value="@{classname}"/>
</replacetokens>
</filterchain>
</loadfile>
<echo level="info">Adding Version Registration Code to @{file}</echo>
<concat destfile="@{file}" append="true" fixlastline="true">${@{module}-@{classname}-version}</concat>
</sequential>
</macrodef>
<macrodef name="addlang">
<attribute name="dir" />
<attribute name="module" />
<attribute name="dest" />
<attribute name="lang" default="" />
<attribute name="details" default = ""/>
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}@{lang}_details" value="" />
</then>
<else>
<property name="@{module}@{lang}_details" value=",@{details}" />
</else>
</if>
<if>
<equals arg1="@{lang}" arg2="" />
<then>
<property name="@{module}@{lang}_fullname" value="@{module}" />
</then>
<else>
<property name="@{module}@{lang}_fullname" value="@{module}_@{lang}" />
</else>
</if>
<if>
<available file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<then>
<mkdir dir="${component.langbuilddir}" />
<java jar="${rhino.jar}" fork="true" failonerror="true">
<jvmarg value="-Dfile.encoding=utf-8" />
<arg file="${yrb2jsonconsole.js}" />
<arg file="${yrb2jsonsrc.js}" />
<arg file="@{dir}/${@{module}@{lang}_fullname}.pres" />
<arg file="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" />
</java>
<echo level="info">Wrapping ${component.langbuilddir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="${component.langbuilddir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</then>
<else>
<echo level="info">Wrapping @{dir}/${@{module}@{lang}_fullname}.js in YUI.add, Y.Intl.add</echo>
<loadfile srcfile="@{dir}/${@{module}@{lang}_fullname}.js" property="@{module}@{lang}-strs-loaded" encoding="utf-8" />
</else>
</if>
<copy file="${builddir}/files/langtemplate.txt" tofile="@{dest}/${@{module}@{lang}_fullname}.js" overwrite="true" outputencoding="utf-8">
<filterset>
<filter token="LANG" value="@{lang}" />
<filter token="LANG_MODULE" value="lang/${@{module}@{lang}_fullname}" />
<filter token="STRINGS" value="${@{module}@{lang}-strs-loaded}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="LANG_DETAILS" value="${@{module}@{lang}_details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addmodule">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="info">Wrapping @{file} in YUI.add module</echo>
<copy file="${builddir}/files/moduletemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}" />
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}" />
<filter token="DETAILS" value="${@{module}-details}" />
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addrollup">
<attribute name="file" />
<attribute name="module" />
<attribute name="details" default="" />
<sequential>
<if>
<equals arg1="@{details}" arg2="" />
<then>
<property name="@{module}-details" value="" />
</then>
<else>
<property name="@{module}-details" value=",@{details}" />
</else>
</if>
<loadfile srcfile="@{file}" property="@{module}-@{file}-code" />
<echo level="info">Adding Rollup @{file} using YUI.add</echo>
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{file}" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{file}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="@{module}"/>
<filter token="DETAILS" value="${@{module}-details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
<macrodef name="addlangrollup">
<attribute name="module" />
<attribute name="dir" />
<sequential>
<echo level="info">Registering rollup info for lang files in @{dir} using YUI.add</echo>
<for list="${component.rollup.lang}" param="lang" trim="true">
<sequential>
<loadfile srcfile="@{dir}/@{module}_@{lang}.js" property="@{module}-@{lang}-code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}_@{lang}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}-@{lang}-details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}_@{lang}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}-@{lang}-code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}_@{lang}"/>
<filter token="DETAILS" value=", ${@{module}-@{lang}-details}"/>
</filterset>
</copy>
</sequential>
</for>
<loadfile srcfile="@{dir}/@{module}.js" property="@{module}--code" />
<var name="lang.use" value="{use:[" />
<for list="${component.lang.use}" param="submod" trim="true">
<sequential>
<var name="lang.use" value="${lang.use}'lang/@{submod}'," />
</sequential>
</for>
<var name="lang.use" value="${lang.use}]}" />
<propertyregex property="@{module}--details"
input="${lang.use}"
regexp="(\,\s*?\])"
replace="]"
casesensitive="false" />
<copy file="${builddir}/files/rolluptemplate.txt" tofile="@{dir}/@{module}.js" overwrite="true">
<filterset>
<filter token="CODE" value="${@{module}--code}"/>
<filter token="YUIVAR" value="${yui.variable}" />
<filter token="MODULE" value="lang/@{module}"/>
<filter token="DETAILS" value=", ${@{module}--details}"/>
</filterset>
</copy>
</sequential>
</macrodef>
+
+ <macrodef name="stampcss">
+ <attribute name="module" />
+ <attribute name="file" />
+ <sequential>
+ <loadfile srcfile="${builddir}/files/css-stamp.txt" property="@{module}" >
+ <filterchain>
+ <replacetokens>
+ <token key="MODULE" value="@{module}"/>
+ </replacetokens>
+ </filterchain>
+ </loadfile>
+ <echo level="info">Adding CSS Registration Code to @{file}</echo>
+ <concat destfile="@{file}" append="true" fixlastline="true">${@{module}}</concat>
+ </sequential>
+ </macrodef>
</project>
|
yui/builder
|
cb924497e8254f220b4c752aa198fabedd5a83ed
|
One more local to remove for multi-skins 1.7 compatibility
|
diff --git a/componentbuild/shared/targets.xml b/componentbuild/shared/targets.xml
index b37a0af..ee54c77 100644
--- a/componentbuild/shared/targets.xml
+++ b/componentbuild/shared/targets.xml
@@ -1,202 +1,202 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiSharedTargets">
<echo level="info">Starting Build For ${component}</echo>
<echo level="info">Ant Properties</echo>
<echo level="info"> Home : ${ant.home}</echo>
<echo level="info"> Ant Version : ${ant.version}</echo>
<echo level="info"> Build File : ${ant.file}</echo>
<echo level="info">Local Build Properties</echo>
<echo level="info"> version : ${yui.version}</echo>
<echo level="info"> srcdir : ${srcdir}</echo>
<echo level="info"> builddir : ${builddir}</echo>
<echo level="info"> component : ${component}</echo>
<echo level="info"> component.basefilename : ${component.basefilename}</echo>
<echo level="info"> component.basedir : ${component.basedir}</echo>
<echo level="info"> component.builddir : ${component.builddir}</echo>
<echo level="info">Global Build Properties</echo>
<echo level="info"> global.build.base : ${global.build.base}</echo>
<echo level="info"> global.build.component : ${global.build.component}</echo>
<echo level="info"> global.build.component.assets : ${global.build.component.assets}</echo>
<dirname property="targets.basedir" file="${ant.file.YuiSharedTargets}"/>
<import file="${targets.basedir}/macrolib.xml" description="Macrodef definitions - jslint, yuicompessor, registerversion" />
<target name="all" depends="local, deploy" description="Build and Deploy to Global Build Directory" />
<target name="local" depends="clean, init, build, minify, lint" description="Build and Deploy to Local Build Directory" />
<target name="init">
<tstamp/>
<mkdir dir="${component.builddir}" />
<createdetails />
<antcall target="-lint-server"/>
</target>
<target name="-lint-server" description="Start JSLint Server" unless="lint.skip">
<antcall target="-node">
<param name="src" value="${builddir}/lib/jslint/jslint-node.js"/>
</antcall>
</target>
<target name="-node" description="Start NodeJS Server" unless="node.spawn">
<if>
<not>
<http url="${node.jslint.url}"/>
</not>
<then>
<!-- You can't set failifexecutionfails if spawn is true. Argh. -->
<!-- Check if it's installed first. -->
<exec resultproperty="node.status" executable="node" failonerror="false" failifexecutionfails="false" searchpath="true" resolveexecutable="true">
<arg value="-v"/>
</exec>
<if>
<equals arg1="${node.status}" arg2="0"/>
<then>
<echo level="info">Spawning Node.js app at: ${src}</echo>
<exec executable="node" spawn="true" failonerror="false" searchpath="true" resolveexecutable="true">
<arg value="${src}"/>
</exec>
</then>
<else>
<echo level="info">For faster builds, install Node.js.</echo>
</else>
</if>
<!-- Don't fail if node doesn't exist, fails to start, etc.
We will fallback to the slow Rhino engine later. -->
</then>
</if>
<!-- Don't try to start again. -->
<property name="node.spawn" value="true"/>
</target>
<target name="clean" description="Clean Local Build Directory" unless="clean.skip">
<delete dir="${component.builddir}" />
</target>
<target name="build" />
<!-- MIN -->
<target name="minify" description="Create component-min.js from component.js">
<yuicompress src="${component.builddir}/${component.basefilename}.js" dest="${component.builddir}/${component.basefilename}-min.js" args="${yuicompressor.js.args.internal}" />
<if>
<available file="${component.builddir}/lang" type="dir" />
<then>
<for param="file">
<path>
<fileset dir="${component.builddir}/lang" includes="*.js"/>
</path>
<sequential>
<yuicompress src="@{file}" dest="@{file}" args="${yuicompressor.js.args.internal}" />
</sequential>
</for>
</then>
</if>
</target>
<target name="lint" description="Run jslint over the local build files (default settings)" unless="lint.skip">
<jslint>
<jsfiles>
<fileset dir="${component.builddir}" includes="*.js" />
</jsfiles>
</jslint>
</target>
<!-- DEPLOY -->
<target name="deploy" description="Copy files to global location" depends="deploybuild, deployassets, deployskins, deploylang, deploydocs"></target>
<target name="deploybuild" description="Copy built files to global build location">
<copy todir="${global.build.component}" overwrite="true" verbose="true">
<fileset dir="${component.builddir}" includes="*.js" />
</copy>
</target>
<target name="deployassets" if="component.assets.exist">
<copy todir="${global.build.component.assets}" flatten="${component.assets.flatten}" overwrite="true" verbose="true">
<fileset dir="${component.assets.base}" includes="${component.assets.files}" excludes="skins/, legacy/" />
</copy>
<copy todir="${global.build.component.assets}" flatten="${component.assets.legacy.flatten}" preservelastmodified="true" failonerror="false" verbose="true">
<fileset dir="${component.assets.legacy.base}" includes="${component.assets.legacy.files}" excludes="skins/" />
</copy>
</target>
<target name="deployskins" if="skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
- <local name="skin.name"/>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Deploying Skin files for @{skin.dir} :: ${skin.name}</echo>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="true">
<fileset dir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" />
</copy>
<copy todir="${global.build.component.assets}/skins/${skin.name}" overwrite="true" verbose="true">
<fileset dir="${component.assets.skins.base}/${skin.name}" includes="${component.assets.skins.files}" />
</copy>
+ <var name="skin.name" unset="true" />
</sequential>
</for>
</target>
<target name="deploylang" description="Copy language bundles to global build location">
<copy todir="${global.build.component}/lang" overwrite="true" failonerror="false" verbose="true">
<fileset dir="${component.builddir}/lang" includes="*.js" />
</copy>
</target>
<target name="deploydocs" description="Copy doc files to global doc locations">
<!-- TODO -->
</target>
<target name="-prepend" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true">
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
<concat destfile="${workingdir}/${component.basefilename}.js.tmp" fixlastline="true" append="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<move file="${workingdir}/${component.basefilename}.js.tmp" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-append" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replaceregex
pattern="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</tokenfilter>
</filterchain>
</concat>
</target>
<target name="-prependdebug" if="component.prependfiles">
<concat destfile="${workingdir}/${component.basefilename}-debug.js.tmp" fixlastline="true" >
<filelist dir="${component.basedir}" files="${component.prependfiles}" />
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
<move file="${workingdir}/${component.basefilename}-debug.js.tmp" tofile="${component.builddir}/${component.basefilename}-debug.js" />
</target>
<target name="-appenddebug" if="component.appendfiles">
<concat destfile="${component.builddir}/${component.basefilename}-debug.js" fixlastline="true" append="true">
<filelist dir="${component.basedir}" files="${component.appendfiles}" />
</concat>
</target>
</project>
|
yui/builder
|
5c6b1664c0dea0ed27af0f555e6aee99d3c6200a
|
Try and make multi-skin support 1.7 compatible
|
diff --git a/componentbuild/3.x/module.xml b/componentbuild/3.x/module.xml
index 73e2f75..4e0c92f 100644
--- a/componentbuild/3.x/module.xml
+++ b/componentbuild/3.x/module.xml
@@ -1,170 +1,170 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="YuiModuleTargets">
<dirname property="module.basedir" file="${ant.file.YuiModuleTargets}"/>
<import file="${module.basedir}/../shared/targets.xml" description="Targets common to Rollup/Module" />
<target name="build" depends="buildcore, -rollupjs, buildskins, buildlangs" />
<target name="buildskins" depends="-buildskins, -rollupcss" />
<target name="buildlangs" depends="-buildlangs, -rolluplangs" />
<!-- CORE -->
<target name="buildcore" depends="builddebug, -createcore, -loggerregex" description="Create component.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}.js" eol="${buildfiles.eol}" />
</target>
<target name="-createcore">
<copy file="${component.builddir}/${component.basefilename}-debug.js" tofile="${component.builddir}/${component.basefilename}.js" />
</target>
<target name="-loggerregex" description="Replace logger statements" unless="component.logger.regex.skip">
<echo level="info">Replacing Logger Statements in ${component.builddir}/${component.basefilename}.js</echo>
<replaceregexp file="${component.builddir}/${component.basefilename}.js"
byline="${component.logger.regex.byline}"
match="${component.logger.regex}"
replace="${component.logger.regex.replace}"
flags="${component.logger.regex.flags}" />
</target>
<!-- DEBUG -->
<target name="builddebug" depends="-concatdebug, -registerdebug, -prependdebug, -appenddebug" description="Create component-debug.js">
<fixcrlf srcdir="${component.builddir}" includes="${component.basefilename}-debug.js" eol="${buildfiles.eol}" />
</target>
<target name="-concatdebug">
<concatsource destfile="${component.builddir}/${component.basefilename}-debug.js" sourcedir="${component.jsfiles.base}" sourcefiles="${component.jsfiles}" />
</target>
<target name="-registerdebug" unless="register.skip">
<addmodule module="${component.module}" file="${component.builddir}/${component.basefilename}-debug.js" details="${component.details.hash}" />
</target>
<target name="-rollupjs" if="rollup">
<if>
<isset property="rollup.sub"/>
<then>
<echo level="info">Module: Build a rollup of a rollup; moving rollup.sub properties into rollup properties.</echo>
<var name="rollup.builddir" unset="true"/>
<var name="rollup.component" unset="true"/>
<var name="rollup.component.basefilename" unset="true"/>
<propertycopy name="rollup.builddir" from="rollup.sub.builddir"/>
<propertycopy name="rollup.component" from="rollup.sub.component"/>
<propertycopy name="rollup.component.basefilename" from="rollup.sub.component.basefilename"/>
</then>
</if>
<echo level="info">Module: Rolling up ${component.basefilename}-debug.js into ${rollup.component.basefilename}-debug.js</echo>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}.js" />
</concat>
<concat destfile="${rollup.builddir}/${rollup.component.basefilename}-debug.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}" files="${component.basefilename}-debug.js" />
</concat>
</target>
<!-- SKINS -->
<target name="-buildskins" depends="-concatskins" description="Create skin rollup in local component build directory" if="component.skins.exist">
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
- <local name="skin.name"/>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Fixing CRLF for Skin files for @{skin.dir} :: ${skin.name}</echo>
<fixcrlf srcdir="${component.builddir}/assets/skins/${skin.name}" includes="${component}.css" eol="${buildfiles.eol}" />
+ <var name="skin.name" unset="true" />
</sequential>
</for>
<!--fixcrlf srcdir="${component.builddir}/assets/skins/sam" includes="${component}.css" eol="${buildfiles.eol}" /-->
</target>
<target name="-buildlangs" description="Create language packs in the local component build directory" if="component.langs.exist">
<mkdir dir="${component.builddir}/lang" />
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<addlang dir="${component.lang.base}" module="${component}" lang="@{lang}" dest="${component.builddir}/lang" />
</sequential>
</for>
<addlang dir="${component.lang.base}" module="${component}" lang="" dest="${component.builddir}/lang/" />
</target>
<target name="-rolluplangs" if="rolluplangs">
<for list="${component.lang}" param="lang" trim="true">
<sequential>
<concat destfile="${rollup.builddir}/lang/${rollup.component}_@{lang}.js" append="true" fixlastline="true">
<fileset dir="${component.builddir}/lang" includes="*_@{lang}.js" />
</concat>
</sequential>
</for>
<concat destfile="${rollup.builddir}/lang/${rollup.component}.js" append="true" fixlastline="true">
<filelist dir="${component.builddir}/lang" files="${component}.js" />
</concat>
</target>
<target name="-concatskins" if="component.skins.exist">
<echo level="info">Concating Skins</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
- <local name="skin.name"/>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concatsource destfile="${component.builddir}/assets/skins/${skin.name}/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/${skin.name}/${component}-skin.css" />
<yuicompress type="css" src="${component.builddir}/assets/skins/${skin.name}/${component}.css" dest="${component.builddir}/assets/skins/${skin.name}/${component}.css" args="${yuicompressor.css.args.internal}" />
+ <var name="skin.name" unset="true" />
</sequential>
</for>
<!--concatsource destfile="${component.builddir}/assets/skins/sam/${component}.css" sourcedir="${component.assets.base}" sourcefiles="${component}-core.css, skins/sam/${component}-skin.css" />
<yuicompress type="css" src="${component.builddir}/assets/skins/sam/${component}.css" dest="${component.builddir}/assets/skins/sam/${component}.css" args="${yuicompressor.css.args.internal}" /-->
</target>
<target name="-rollupcss" if="rollupskins">
<echo level="info">Rolling up ${component}.css into ${rollup.component}.css</echo>
<for param="skin.dir">
<path>
<dirset dir="${component.assets.base}/skins/" includes="*"/>
</path>
<sequential>
- <local name="skin.name"/>
<basename property="skin.name" file="@{skin.dir}"/>
<echo level="info">Concating Skin files for @{skin.dir} :: ${skin.name}</echo>
<concat destfile="${rollup.builddir}/assets/skins/${skin.name}/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/${skin.name}" files="${component}.css" />
</concat>
+ <var name="skin.name" unset="true" />
</sequential>
</for>
<!--concat destfile="${rollup.builddir}/assets/skins/sam/${rollup.component}.css" append="true" fixlastline="true">
<filelist dir="${component.builddir}/assets/skins/sam" files="${component}.css" />
</concat-->
</target>
<!-- Tests -->
<target name="tests" depends="-lint-server">
<echo level="info">Generating test module for ${component}</echo>
<echo level="info"> Test module: ${tests.component}</echo>
<echo level="info"> Test module source directory: ${tests.srcdir}</echo>
<echo level="info"> Test module source files: ${tests.jsfiles}</echo>
<echo level="info"> Test module output directory: ${tests.builddir}</echo>
<echo level="info"> Test module file: ${tests.builddir}/${tests.component}.js</echo>
<echo level="info"> </echo>
<available file="${tests.srcdir}" type="dir" property="tests.srcdir.exists"/>
<var name="buildfile" value="${tests.builddir}/${tests.component}.js"/>
<arrayliteral from="tests.requires" to="tests.details.requires" key="requires"/>
<concatsource destfile="${buildfile}" sourcedir="${tests.srcdir}" sourcefiles="${tests.jsfiles}"/>
<addmodule file="${buildfile}" module="${tests.component}" details="{${tests.details.requires}}"/>
<jslint>
<jsfiles>
<fileset file="${buildfile}"/>
</jsfiles>
</jslint>
<echo level="info">Test module ${tests.component} created</echo>
</target>
</project>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.