require "rjb" require "core/project" module Buildr # Base module for all things Java. module Java # Options accepted by #java and other methods here. JAVA_OPTIONS = [ :verbose, :classpath, :name, :java_args, :properties ] # Classpath dependencies available when running JUnit. JUNIT_REQUIRES = [ "junit:junit:jar:3.8.1", "jmock:jmock:jar:1.1.0" ] # Returned by Java#rjb, you can use this object to set the RJB classpath, specify blocks to be invoked # after loading RJB, and load RJB itself. # # RJB can be loaded exactly once, and once loaded, you cannot change its classpath. Of course you can # call libraries that manage their own classpath, but the lazy way is to just tell RJB of all the # classpath dependencies you need in advance, before loading it. # # For that reason, you should not load RJB until the moment you need it. You can call #load or call # Java#rjb with a block. For the same reason, you may need to specify code to execute when loading # (see #onload). class RjbWrapper include Singleton def initialize() #:nodoc: @classpath = [Java.tools_jar] @onload = [] onload do onload do Rjb.load(Buildr.artifacts(classpath).each { |task| task.invoke if task.respond_to?(:invoke) }. map(&:to_s).join(File::PATH_SEPARATOR)) end end end # The classpath used when loading RJB. attr_accessor :classpath # :call-seq: # onload { ... } # # Adds a block to call when loading RJB and returns self. # # You can only load RJB once, and you may need to do some tasks after the initial load. # For example, the Ant module requires Antwrap which can only be loaded after RJB. def onload(&block) @onload << block self end # :call-seq: # load() # # Loads RJB. You can also call Java#ejb with a block to get the same effect. def load() @onload.each(&:call) @onload.clear end def method_missing(sym, *args, &block) #:nodoc: Rjb.send sym, *args, &block end end class << self # :call-seq: # version() => string # # Returns the version number of the JVM. # # For example: # puts Java.version # => 1.5.0_10 def version() @version ||= `#{path_to_bin("java")} -version 2>&1`.scan(/java version "(.*)"/)[0][0] end # :call-seq: # tools_jar() => path # # Returns a path to tools.jar. def tools_jar() unless @tools home = ENV["JAVA_HOME"] || File.dirname(File.dirname(`which java`.split.first)) tools = File.join(home, "lib/tools.jar") @tools = tools if File.exist?(tools) end @tools end # :call-seq: # java(class, *args, options?) # # Runs Java with the specified arguments. # # The last argument may be a Hash with additional options: # * :classpath -- One or more file names, tasks or artifact specifications. # These are all expanded into artifacts, and all tasks are invoked. # * :java_args -- Any additional arguments to pass (e.g. -hotspot, -xms) # * :properties -- Hash of system properties (e.g. "path"=>base_dir). # * :name -- Shows this name, otherwise shows the first argument (the class name). # * :verbose -- If true, prints the command and all its argument. def java(*args) options = Hash === args.last ? args.pop : {} options[:verbose] ||= Rake.application.options.trace || false fu_check_options options, *JAVA_OPTIONS name = options[:name] || "java #{args.first}" cmd_args = [] classpath = classpath_from(options) cmd_args << "-cp" << classpath.join(File::PATH_SEPARATOR) unless classpath.empty? options[:properties].each { |k, v| cmd_args << "-D#{k}=#{v}" } if options[:properties] cmd_args += options[:java_args].flatten if options[:java_args] cmd_args += args.flatten.compact cmd_args << { :verbose=>options[:verbose] } unless Rake.application.options.dryrun puts "Running #{name}" if verbose sh(path_to_bin("java"), *cmd_args) { |ok, res| fail "Failed to execute #{name}, see errors above" unless ok } end end # :call-seq: # apt(*files, options) # # Runs Apt with the specified arguments. # # The last argument may be a Hash with additional options: # * :compile -- If true, compile source files to class files. # * :source -- Specifies source compatibility with a given JVM release. # * :output -- Directory where to place the generated source files, or the # generated class files when compiling. # * :classpath -- One or more file names, tasks or artifact specifications. # These are all expanded into artifacts, and all tasks are invoked. def apt(*args) options = Hash === args.last ? args.pop : {} fu_check_options options, :compile, :source, :output, :classpath files = args.flatten.map(&:to_s). collect { |arg| File.directory?(arg) ? FileList["#{arg}/**/*.java"] : arg }.flatten cmd_args = [ Rake.application.options.trace ? "-verbose" : "-nowarn" ] if options[:compile] cmd_args << "-d" << options[:output].to_s else cmd_args << "-nocompile" << "-s" << options[:output].to_s end cmd_args << "-source" << options[:source] if options[:source] classpath = classpath_from(options) cmd_args << "-cp" << classpath.join(File::PATH_SEPARATOR) unless classpath.empty? cmd_args += files unless Rake.application.options.dryrun puts "Running apt" if verbose puts (["apt"] + cmd_args).join(" ") if Rake.application.options.trace Java.rjb do |rjb| rjb.import("com.sun.tools.apt.Main").process(cmd_args) == 0 or fail "Failed to process annotations, see errors above" end end end # :call-seq: # javac(*files, options) # # Runs Javac with the specified arguments. # # The last argument may be a Hash with additional options: # * :output -- Target directory for all compiled class files. # * :classpath -- One or more file names, tasks or artifact specifications. # These are all expanded into artifacts, and all tasks are invoked. # * :sourcepath -- Additional source paths to use. # * :javac_args -- Any additional arguments to pass (e.g. -extdirs, -encoding) # * :name -- Shows this name, otherwise shows the working directory. def javac(*args) options = Hash === args.last ? args.pop : {} fu_check_options options, :classpath, :sourcepath, :output, :javac_args, :name files = args.flatten.each { |f| f.invoke if f.respond_to?(:invoke) }.map(&:to_s). collect { |arg| File.directory?(arg) ? FileList["#{arg}/**/*.java"] : arg }.flatten name = options[:name] || Dir.pwd cmd_args = [] classpath = classpath_from(options) cmd_args << "-cp" << classpath.join(File::PATH_SEPARATOR) unless classpath.empty? cmd_args << "-sourcepath" << options[:sourcepath].join(File::PATH_SEPARATOR) if options[:sourcepath] cmd_args << "-d" << options[:output].to_s if options[:output] cmd_args += options[:javac_args].flatten if options[:javac_args] cmd_args += files unless Rake.application.options.dryrun puts "Compiling #{files.size} source files in #{name}" if verbose puts (["javac"] + cmd_args).join(" ") if Rake.application.options.trace Java.rjb do |rjb| rjb.import("com.sun.tools.javac.Main").compile(cmd_args) == 0 or fail "Failed to compile, see errors above" end end end # :call-seq: # javadoc(*files, options) # # Runs Javadocs with the specified files and options. # # This method accepts the following special options: # * :output -- The output directory # * :classpath -- Array of classpath dependencies. # * :sourcepath -- Array of sourcepaths (paths or tasks). # * :name -- Shows this name, otherwise shows the working directory. # # All other options are passed to Javadoc as following: # * true -- As is, for example, :author=>true becomes -author # * false -- Prefixed, for example, :index=>false becomes -noindex # * string -- Option with value, for example, :windowtitle=>"My project" becomes -windowtitle "My project" # * array -- Option with set of values separated by spaces. def javadoc(*args) options = Hash === args.last ? args.pop : {} cmd_args = [ "-d", options[:output], Rake.application.options.trace ? "-verbose" : "-quiet" ] options.reject { |key, value| [:output, :name, :sourcepath, :classpath].include?(key) }. each { |key, value| value.invoke if value.respond_to?(:invoke) }. each do |key, value| case value when true, nil cmd_args << "-#{key}" when false cmd_args << "-no#{key}" when Array cmd_args << "-#{key}" cmd_args += value.map(&:to_s) when Hash value.each { |k,v| cmd_args << "-#{key}" << k.to_s << v.to_s } else cmd_args << "-#{key}" << value.to_s end end [:sourcepath, :classpath].each do |option| options[option].to_a.flatten.tap do |paths| cmd_args << "-#{option}" << paths.flatten.map(&:to_s).join(File::PATH_SEPARATOR) unless paths.empty? end end cmd_args += args.flatten.uniq name = options[:name] || Dir.pwd unless Rake.application.options.dryrun puts "Generating Javadoc for #{name}" if verbose puts (["javadoc"] + cmd_args).join(" ") if Rake.application.options.trace Java.rjb do |rjb| rjb.import("com.sun.tools.javadoc.Main").execute(cmd_args) == 0 or fail "Failed to generate Javadocs, see errors above" end end end # :call-seq: # junit(*classes, options) => [ passed, failed ] # # Runs JUnit test cases from the specified classes. Returns an array with two lists, # one containing the names of all classes that passes, the other containing the names # of all classes that failed. # # The last argument may be a Hash with additional options: # * :classpath -- One or more file names, tasks or artifact specifications. # These are all expanded into artifacts, and all tasks are invoked. # * :properties -- Hash of system properties (e.g. "path"=>base_dir). # * :verbose -- If true, prints the command and all its argument. def junit(*args) options = Hash === args.last ? args.pop : {} options[:verbose] ||= Rake.application.options.trace || false fu_check_options options, :verbose, :classpath, :properties classpath = classpath_from(options) + junit_artifacts tests = args.flatten failed = tests.inject([]) do |failed, test| begin java "junit.textui.TestRunner", test, :classpath=>classpath, :properties=>options[:properties], :name=>"#{test}", :verbose=>options[:verbose] failed rescue failed << test end end [ tests - failed, failed ] end # :call-seq: # rjb() => RjbWrapper # rjb() { ... } # # This method can be used in two ways. Without a block, returns the RjbWrapper # object which you can use to configure the RJB classpath or call other RJB methods. # With a block, loads RJB and yields to the block, returning its result. # # For example: # Java.rjb.classpath += REQUIRES # Java.rjb.onload { require "antwrap" } # . . . # # def execute(name, options) # options = options.merge(:name=>name, :base_dir=>Dir.pwd, :declarative=>true) # Java.rjb { AntProject.new(options) } # end def rjb() if block_given? RjbWrapper.instance.load yield RjbWrapper.instance else RjbWrapper.instance end end # :call-seq: # path_to_bin(cmd?) => path # # Returns the path to the specified Java command (with no argument to java itself). # Uses JAVA_HOME if set, otherwise assumes the command is accessible from the path. def path_to_bin(name = "java") ENV["JAVA_HOME"] ? File.join(ENV["JAVA_HOME"], "bin", name) : name end protected # :call-seq: # classpath_from(options) => files # # Extracts the classpath from the options, expands it by calling artifacts, invokes # each of the artifacts and returns an array of paths. def classpath_from(options) classpath = (options[:classpath] || []).collect Buildr.artifacts(classpath).each { |t| t.invoke if t.respond_to?(:invoke) }.map(&:to_s) end # :call-seq: # junit_artifacts() => files # # Returns the JUnit artifacts as paths, after downloading and installing them (if necessary). def junit_artifacts() @junit_artifacts ||= Buildr.artifacts(JUNIT_REQUIRES).each { |task| task.invoke }.map(&:to_s) end end # See Java#java. def java(*args) Java.java(*args) end # :call-seq: # apt(*sources) => task # # Returns a task that will use Java#apt to generate source files in target/generated/apt, # from all the source directories passed as arguments. Uses the compile.sources list if # on arguments supplied. # # For example: # def apt(*sources) sources = compile.sources if sources.empty? file(path_to("target/generated/apt")=>sources) do |task| Java.apt(sources.map(&:to_s) - [task.name], :output=>task.name, :classpath=>compile.classpath, :source=>compile.options.source) end end end include Java end