VoiceOfUnreason
VoiceOfUnreason

Reputation: 57279

Excluding jars from dynamically generated classpaths?

I'm launching my java server from a bash script. The server has "provided" dependencies on 3rd party jars. However, some of those jars conflict with jars in my app, and need to be excluded from the classpath...

At the moment, I only need to exclude one jar, so this idiom gets me by

EXTERNAL_JARS=$(find "${EXTERNAL_LIB}" -name 'slf4j-log4j12-1.4.3.jar' -prune -o -type f -name '*.jar' -printf ':%p' )
CLASSPATH=${CLASSPATH}${EXTERNAL_JARS}

Is there a better approach to use when the number of external jars is 20-30 and the number of excluded jars is ~ 5 ?

Upvotes: 3

Views: 3645

Answers (1)

carl.anderson
carl.anderson

Reputation: 1128

This would work, although it assumes that you don't have spaces in your filenames.

EXCLUDED="slf4j-log4j12-1.4.3.jar
some-other-library.jar
something-else.jar"

EXTERNAL_JARS=$(
  find "${EXTERNAL_LIB}" -type f -name '*.jar' \
    | grep -v -F"$EXCLUDED" \
    | xargs \
    | tr ' ' ':'
)

CLASSPATH=${CLASSPATH}:${EXTERNAL_JARS}

The idea here is to use grep -v -F and a multi-line string variable to filter out the excluded jars.

When you do that, you can no longer use the -printf flag in find, so you replace it with xargs | tr ' ' '-'. Here xargs will concatenate all the jars, separating them with a space and the tr command replaces those spaces with colons. Again, this will work if you don't have spaces in your path.

Upvotes: 2

Related Questions