I've been developing applications in JRuby lately and really enjoying it, but I've been running into a wall when it comes to packaging my project into a JAR file when it includes external Java libraries. If the project does not depend on any external Java library JAR files, I run into no problems.
Below is an example application. This code works perfectly fine when running the ./bin/my_proj executable. But, when I package it into a JAR file, the external Java library cannot be loaded because it is not found on the CLASSPATH.
When I unpackage my application's JAR file, I can see that it includes all of my code as well as the vendor directory containing the external Java library. So, everything's where it should be.
lib/my_proj/application.rb
java_import 'com.somecompany.somejavalibrary.SomeJavaLibraryClass'
module MyProj
class Application < SomeJavaLibraryClass
# Some code implementing SomeJavaLibraryClass
end
end
lib/my_proj.rb
require 'pathname'
module MyProj
def root
Pathname.new(__FILE__).join('..', '..').expand_path
end
def start
setup_environment
Application.new
end
def setup_environment
@setup ||= false
unless @setup
@setup = true
require 'java'
$CLASSPATH << root.join('vendor').to_s # Setup Java CLASSPATH
$LOAD_PATH << root.join('lib').to_s # Setup Ruby LOAD_PATH
require 'some_java_library' # Load the external Java library from it's JAR
require 'my_proj/application'
end
end
extend self
end
bin/my_proj
#!/usr/bin/env ruby
$:.unshift File.expand_path( File.join('..', '..', 'lib'), __FILE__ )
require 'my_proj'
MyProj.start
config/warble.rb
Warbler::Config.new do |config|
config.features = %w(gemjar compiled)
config.autodeploy_dir = 'pkg'
config.dirs = %w(assets bin config lib)
config.java_libs += FileList['vendor/*.jar']
end
vendor/some_java_library.jar
# This is the external Java library
The external jars should be in the lib folder.
You can add them in code by doing something like
$CLASSPATH << "vendor/some_java_library.jar" #or loop the directory for all jars and add them
Or you can create a META-INF/MANIFEST.MF file and specifiy the CLASSPATH jars
and adding a line like
Class-Path: vendor/some_java_library.jar jar2-name directory-name/jar3-name
http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With