Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Scala Script with external dependencies

I have the following jars under /Users/joe/.scala/lib:

commons-codec-1.4.jar       
httpclient-4.1.1.jar        
httpcore-4.1.jar
commons-logging-1.1.1.jar   
httpclient-cache-4.1.1.jar  
httpmime-4.1.1.jar

Below is my test.sh written in scala.

#!/bin/sh -v
L=`cd /Users/joe/.scala/lib;pwd`
cp=`echo $L/*.jar|sed 's/ /:/g'`
echo $cp
exec scala -classpath $cp $0 $@
!#
println(new org.apache.commons.httpclient.HttpClient())

Here is the error that I get:

$ ./test.sh 
#!/bin/sh -v
L=`cd /Users/joe/.scala/lib;pwd`
cd /Users/joe/.scala/lib;pwd
cp=`echo $L/*.jar|sed 's/ /:/g'`
echo $L/*.jar|sed 's/ /:/g'
echo $cp
/Users/joe/.scala/lib/commons-codec-1.4.jar:/Users/joe/.scala/lib/commons-logging-1.1.1.jar:/Users/joe/.scala/lib/httpclient-4.1.1.jar:/Users/joe/.scala/lib/httpclient-cache-4.1.1.jar:/Users/joe/.scala/lib/httpcore-4.1.jar:/Users/joe/.scala/lib/httpmime-4.1.1.jar
exec scala -classpath $cp $0 $@
/Users/joe/Desktop/scala/./test.sh:7: error: object httpclient is not a member of package org.apache.commons
println(new org.apache.commons.httpclient.HttpClient())
                               ^
one error found

However, simple ones without any classpath dependencies work though: hello.sh

#!/bin/sh
exec scala "$0" "$@"
!#

println(new java.util.Date())

Any idea what I am doing wrong in the first example? Alternatively, what is the best way to set classpath dependencies when working with scala scripts?

like image 223
Langali Avatar asked Jun 14 '11 22:06

Langali


2 Answers

I'm not going to answer your question, but you might be interested in this.

Suppose you download and install SBT (version 0.10.0 or higher), and create a shell script called "scalas":

java -Dsbt.main.class=sbt.ScriptMain \
     -Dsbt.boot.directory=/home/user/.sbt/boot \
     -jar sbt-launch.jar "$@"

And then you write your script like this:

#!/usr/bin/env scalas
!#

/***
scalaVersion := "2.9.1"

libraryDependencies ++= Seq(
  "commons-codec" % "commons-codec" % "1.4", 
  "org.apache.httpcomponents" % "httpclient" % "4.1.1",
  "org.apache.httpcomponents" % "httpcore" % "4.1",
  "commons-logging" % "commons-logging" % "1.1.1",
  "org.apache.httpcomponents" % "httpclient-cache" % "4.1.1", 
  "org.apache.httpcomponents" % "httpmime" % "4.1.1"
)
*/

println(new org.apache.http.client.DefaultHttpClient())
like image 148
Daniel C. Sobral Avatar answered Oct 12 '22 07:10

Daniel C. Sobral


I think with 4.1.1 the class is org.apache.http.client.HttpClient instead of org.apache.commons.httpclient, and it's an interface. So you might want

new org.apache.http.client.DefaultHttpClient()

instead of

new org.apache.commons.httpclient.HttpClient()

It might well have been different in an earlier version.

like image 27
Don Roby Avatar answered Oct 12 '22 09:10

Don Roby