use of groovy.lang.Script in project beakerx by twosigma.
the class GroovyEvaluatorTest method parseClassFromScript.
public Object parseClassFromScript(String script) {
Class<?> parsedClass = groovyClassLoader.parseClass(script);
Script instance = null;
try {
instance = (Script) parsedClass.newInstance();
instance.setBinding(scriptBinding);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return instance.run();
}
use of groovy.lang.Script in project groovity by disney.
the class Groovity method getChangedSources.
public List<GroovitySource> getChangedSources() {
ArrayList<GroovitySource> changedSources = new ArrayList<GroovitySource>();
if (sourceLocators != null) {
ArrayList<String> currentScripts = new ArrayList<String>(((Map<String, Long>) scriptDates).keySet());
for (GroovitySourceLocator sourceLocator : sourceLocators) {
for (GroovitySource source : sourceLocator) {
String key = fixCase(source.getPath());
if (key.endsWith(GROOVITY_SOURCE_EXTENSION)) {
key = key.substring(0, key.length() - 5);
}
if (scriptDates.containsKey(key)) {
currentScripts.remove(key);
if (!source.exists() || source.getLastModified() != scriptDates.get(key)) {
changedSources.add(source);
}
} else if (source.exists()) {
changedSources.add(source);
}
}
}
for (final String script : currentScripts) {
// these have been deleted
Class<Script> delClass = scripts.get(script);
final String path = getSourcePath(delClass);
changedSources.add(new GroovitySource() {
public String getSourceCode() throws IOException {
return "";
}
public String getPath() {
return path;
}
public long getLastModified() {
return System.currentTimeMillis();
}
public boolean exists() {
return false;
}
});
}
}
return changedSources;
}
use of groovy.lang.Script in project groovity by disney.
the class Groovity method loadClasses.
protected void loadClasses(String sourcePath, InputStream jarStream, long modTime, boolean embedded, HashMap<String, Collection<String>> newScriptDependencies, Map<String, Boolean> newScriptInits) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
ArrayList<String> dependencies = new ArrayList<String>();
CompilerConfiguration compilerConfiguration = createCompilerConfiguration(null, dependencies);
GroovyClass[] classes = loadGroovyClasses(jarStream);
// a classloader only gets the traits that are available when it is created, so we make a copy
@SuppressWarnings("rawtypes") ConcurrentHashMap<String, Class> traitsCopy = new ConcurrentHashMap<>(traits);
GroovityClassLoader loader = parentLoader != null ? new GroovityClassLoader(sourcePath, parentLoader, compilerConfiguration, this, cacheRefreshExecutor, traitsCopy) : new GroovityClassLoader(sourcePath, Thread.currentThread().getContextClassLoader(), compilerConfiguration, this, cacheRefreshExecutor, traitsCopy);
if (classes != null) {
Class<Script> scriptClass = loadGroovyClassesAndFindScript(loader, classes, traits, traitsCopy);
if (scriptClass != null) {
// this seemingly useless call will force failure if there are referenced traits missing so we can retry ...
for (@SuppressWarnings("rawtypes") Class c : loader.getLoadedClasses()) {
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
f.getGenericType();
}
Method[] dm = c.getDeclaredMethods();
for (Method m : dm) {
m.getGenericParameterTypes();
m.getGenericReturnType();
m.getGenericExceptionTypes();
}
}
String path = getSourcePath(scriptClass);
String script = getScriptName(path);
String fixed = fixCase(script);
// System.out.println("Loaded script "+script+" for name "+path+" "+scriptClass);
newScriptDependencies.put(script, getDependencies(scriptClass));
newScriptInits.put(script, hasInit((GroovityClassLoader) scriptClass.getClassLoader()));
if (embedded) {
embeddedScripts.put(fixed, scriptClass);
} else {
scripts.put(fixed, scriptClass);
scriptDates.put(fixed, modTime);
}
} else {
log.severe("NO SCRIPT CLASS FOUND!! " + sourcePath);
}
}
}
use of groovy.lang.Script in project groovity by disney.
the class Groovity method getLibraryDocs.
@SuppressWarnings({ "rawtypes", "unchecked" })
public List getLibraryDocs() {
ArrayList docs = new ArrayList();
ArrayList<Map.Entry<String, Class<Script>>> entries = new ArrayList<Map.Entry<String, Class<Script>>>();
entries.addAll(embeddedScripts.entrySet());
entries.addAll(scripts.entrySet());
// alphabetize for consistency
Collections.sort(entries, new Comparator<Map.Entry<String, Class<Script>>>() {
public int compare(Entry<String, Class<Script>> o1, Entry<String, Class<Script>> o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
for (Map.Entry<String, Class<Script>> entry : entries) {
Boolean isLibrary = Boolean.FALSE;
Class scriptClass = entry.getValue();
try {
isLibrary = (Boolean) scriptClass.getField(IS_GROOVITY_LIBRARY).get(scriptClass);
} catch (Exception e) {
}
if (isLibrary.booleanValue()) {
String sourcePath = getSourcePath(scriptClass);
String className = scriptClass.getName();
if (className.startsWith("_")) {
className = className.substring(1);
}
HashSet<Class> publicClasses = new HashSet<Class>();
LinkedHashMap libModel = new LinkedHashMap();
libModel.put(NAME, className);
libModel.put(PATH, sourcePath);
List functions = new ArrayList();
libModel.put(FUNCTIONS, functions);
Method[] methods = entry.getValue().getDeclaredMethods();
Arrays.sort(methods, new Comparator<Method>() {
public int compare(Method o1, Method o2) {
int o = o1.getName().compareTo(o2.getName());
if (o == 0) {
o = o1.getParameterTypes().length - o2.getParameterTypes().length;
}
return o;
}
});
for (Method method : methods) {
Function func = method.getAnnotation(Function.class);
if (func != null && !internalMethodNames.contains(method.getName())) {
LinkedHashMap funcModel = new LinkedHashMap();
funcModel.put(NAME, method.getName());
funcModel.put(INFO, func.info());
functions.add(funcModel);
// add argument info
Type[] pts = method.getGenericParameterTypes();
Annotation[][] panns = method.getParameterAnnotations();
if (pts != null && pts.length > 0 && pts.length == panns.length) {
List params = new ArrayList();
funcModel.put(ARGS, params);
for (int i = 0; i < pts.length; i++) {
Type type = pts[i];
LinkedHashMap argModel = new LinkedHashMap();
params.add(argModel);
Annotation[] arganns = panns[i];
for (Annotation a : arganns) {
if (a.annotationType().equals(Arg.class)) {
Arg arg = (Arg) a;
argModel.put(NAME, arg.name());
argModel.put(INFO, arg.info());
argModel.put(NULLABLE, arg.nullable());
}
}
collectClasses(type, publicClasses, scriptClass.getClassLoader());
argModel.put(TYPE, TypeLabel.get(type));
}
}
// add return type
Type returnType = method.getGenericReturnType();
if (returnType != null) {
collectClasses(returnType, publicClasses, scriptClass.getClassLoader());
funcModel.put(RETURNS, TypeLabel.get(returnType));
}
}
}
if (publicClasses.size() > 0) {
List classDocs = new ArrayList();
libModel.put(CLASSES, classDocs);
for (Class c : publicClasses) {
classDocs.add(makeClassDoc(c));
}
}
docs.add(libModel);
}
}
return docs;
}
use of groovy.lang.Script in project groovity by disney.
the class Groovity method compile.
/**
* Compare the timestamp of the source against an existing compiled version, only recompiling
* if they do not match. The force parameter is used to force a recompile regardless of dates.
*
* @param sources
* @param force
*/
@SuppressWarnings("rawtypes")
protected void compile(boolean force, boolean init, ConcurrentHashMap<String, Class> compilerTraits, GroovitySource... sources) {
// take multiple sources and compile as a set, only initing() classes once all are loaded
HashMap<String, Class<Script>> newScripts = new HashMap<String, Class<Script>>();
HashMap<String, Long> newScriptDates = new HashMap<String, Long>();
HashMap<String, File> deletedScripts = new HashMap<String, File>();
HashMap<String, Collection<String>> scriptDependencies = new HashMap<String, Collection<String>>();
HashMap<String, Boolean> scriptInits = new HashMap<String, Boolean>();
compileLoop(newScripts, newScriptDates, deletedScripts, scriptDependencies, scriptInits, force, init, 0, compilerTraits, sources);
List<Class<Script>> toDestroy = new ArrayList<Class<Script>>();
HashSet<String> sourceNames = new HashSet<>();
for (GroovitySource source : sources) {
sourceNames.add(getScriptName(source.getPath()));
}
List<String> sortedScripts = sortDependencies(scriptDependencies, scriptInits);
// load order for dependencies!
for (String scriptName : sortedScripts) {
String scriptNameFixed = fixCase(scriptName);
Class<Script> theClass = newScripts.get(scriptName);
if (init) {
initClass(theClass);
}
scriptDates.put(scriptNameFixed, newScriptDates.get(scriptName));
Class<Script> oldClass = scripts.put(scriptNameFixed, theClass);
if (listeners != null) {
for (GroovityClassListener listener : listeners) {
listener.scriptUpdated(this, scriptName, theClass);
}
}
if (oldClass != null) {
toDestroy.add(oldClass);
} else if (embeddedScripts.containsKey(scriptNameFixed)) {
toDestroy.add(embeddedScripts.get(scriptNameFixed));
}
}
for (Map.Entry<String, File> deleted : deletedScripts.entrySet()) {
String name = deleted.getKey();
String nameCaseFixed = fixCase(name);
Class<Script> oldClass = scripts.remove(nameCaseFixed);
scriptDates.remove(nameCaseFixed);
// notify listeners
if (listeners != null) {
for (GroovityClassListener listener : listeners) {
listener.scriptDeleted(name);
}
}
if (oldClass != null) {
log.info("Deleting removed source " + name + " / class " + oldClass.getName());
toDestroy.add(oldClass);
Class<Script> embeddedClass = embeddedScripts.get(nameCaseFixed);
if (embeddedClass != null && init) {
initClass(embeddedClass);
newScripts.put(nameCaseFixed, embeddedClass);
}
}
if (deleted.getValue() != null) {
deleted.getValue().delete();
}
}
if (init) {
// now destroy
for (Class<Script> del : toDestroy) {
((GroovityClassLoader) del.getClassLoader()).destroy();
}
if (started.get()) {
// now start new scripts
newScripts.values().forEach(cls -> {
startClass(cls);
});
}
}
Map<String, Throwable> errors = new LinkedHashMap<String, Throwable>();
for (Entry<String, GroovityCompilerEvent> entry : getCompilerEvents().entrySet()) {
if (entry.getValue().getError() != null) {
if (sourceNames.contains(entry.getKey())) {
errors.put(entry.getKey(), entry.getValue().getError());
}
}
}
if (errors.size() > 0) {
StringBuilder messageBuilder = new StringBuilder(String.valueOf(errors.size())).append(" script");
if (errors.size() > 1) {
messageBuilder.append("s");
}
messageBuilder.append(" failed to compile");
for (Entry<String, Throwable> entry : errors.entrySet()) {
messageBuilder.append(LINE_SEPARATOR);
messageBuilder.append(LINE_SEPARATOR);
messageBuilder.append("Error compiling ").append(entry.getKey()).append(".grvt :");
messageBuilder.append(LINE_SEPARATOR);
messageBuilder.append(LINE_SEPARATOR);
messageBuilder.append(entry.getValue().getMessage());
}
log.severe(messageBuilder.toString());
}
}
Aggregations