metridoc.build.RunHelper.groovy Maven / Gradle / Ivy
/*
* Copyright 2010 Trustees of the University of Pennsylvania Licensed under the
* Educational Community License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.osedu.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package metridoc.build
import groovy.ui.GroovyMain
import groovy.util.logging.Slf4j
/**
* Created by IntelliJ IDEA.
* User: tbarker
* Date: 9/26/11
* Time: 2:18 PM
*/
@Slf4j
class RunHelper {
static final separator = System.getProperty("file.separator")
static private boolean runningViaMain = false
/**
* allows jobs to be run in maven or jars
* @param args the jobs to run
*/
public static void main(String[] args) {
runningViaMain = true
runJob(null, args)
}
/**
* provides an extension point for extending scripts for use with use
. If the script is null,
* it is assumed that jobs are being run via main
*
* @param self the script that is running this script with use
* @param args the jobs to run
* @return
*/
def static runJob(Script self, String[] args) {
if(runningViaMain) {
runJobViaMain(args)
} else {
runJobViaFilePath(args)
}
}
def static runJobViaMain(String[] args) {
args.each {
def contextClassLoader = Thread.currentThread().contextClassLoader
Class clazz = contextClassLoader.loadClass(it)
Script script = clazz.newInstance()
script.run()
}
}
def static runJobViaFilePath(String[] args) {
checkClassPath()
def classLoader = Thread.currentThread().contextClassLoader
GroovyShell shell = new GroovyShell(classLoader)
args.each {
def file
if(it.contains(".")) {
def path = it.replaceAll("\\.", separator)
if(!path.startsWith("src")) {
path = "src/${path}"
}
if(path.endsWith("groovy")) {
path = it.replaceAll("/groovy", ".groovy")
} else {
path += ".groovy"
}
file = new File(path)
} else {
file = getFile(new File("src"), it)
}
if(file == null) {
throw new FileNotFoundException("Could not find job ${it}")
}
def script = shell.parse(file)
script.args = args
script.run()
}
}
static File getFile(File file, String name) {
log.debug("searching for job {} in file {}", name, file)
if(file.isDirectory()) {
for(File child : file.listFiles()) {
def result = getFile(child, name)
if(result) {
return result
}
}
}
if("${name}.groovy" == file.name) {
log.info("found job {} at {}", name, file)
return file
}
return null
}
def static checkClassPath() {
addToClassPath("resources")
addToClassPath("src")
}
def static addToClassPath(String path) {
RunHelper.class.classLoader.rootLoader.addURL(toUrl(path))
}
def static toUrl(String path) {
new File(path).toURI().toURL()
}
}