创建ScriptExecutor

<pre>
1. 从jvm system property加载对应的classname
2. 从META-INF/services/加载对应的classname
</pre>
558323
private ScriptExecutor createScriptExecutor() {
        String className = null;
        ClassLoader loader = ScriptExecutor.class.getClassLoader();

        // 1. try the JVM-instance-wide system property
        try {
            className = System.getProperty(property);
        } catch (RuntimeException e) { /* normally fails for applets */
        }

        // 2. if that fails, try META-INF/services/
        if (StringUtils.isEmpty(className)) {
            try {
                String service = "META-INF/services/" + property;
                InputStream in;
                BufferedReader reader;

                if (loader == null) {
                    in = ClassLoader.getSystemResourceAsStream(service);
                } else {
                    in = loader.getResourceAsStream(service);
                }

                if (in != null) {
                    reader = new BufferedReader(new InputStreamReader(in, System.getProperty("file.encoding", "UTF-8")));
                    className = reader.readLine();
                    in.close();
                }
            } catch (Exception e) {
            }
        }

        // 3. Distro-specific fallback
        if (className == null) {
            className = DEFAULT_SCRIPT;
        }

        Class clazz = ReflectionHelper.forName(className, loader);
        return (ScriptExecutor) ReflectionHelper.newInstance(clazz);
    }
858952
public JavaScriptActionBuilder javascript(String script) {
        JavaScriptAction action = new JavaScriptAction();
        action.setScript(script);
        action(action);
        return new JavaScriptActionBuilder(action);
    }
46782
private StringBuffer loadScriptTemplate() {
		try (InputStream is = ClassLoaderResourceUtils.getResourceAsStream(SCRIPT_TEMPLATE, this);
				StringWriter sw = new StringWriter()) {
			IOUtils.copy(is, sw);
			return sw.getBuffer();

		} catch (IOException e) {
			Marker fatal = MarkerFactory.getMarker("FATAL");
			LOGGER.error(fatal, "a serious error occurred when initializing MessageBundleScriptCreator");
			throw new BundlingProcessException(
					"Classloading issues prevent loading the message template to be loaded. ", e);
		}
	}
625538
@SuppressWarnings("unchecked")
	private StringBuffer getInterfaceScript(String scriptName,ServletContext servletContext) {
		StringBuffer sb = new StringBuffer(ENGINE_INIT);

		// List all containers to find all DWR interfaces
		List<Container> containers = ContainerUtil.getAllPublishedContainers(servletContext);
		boolean found = false;
		for(Iterator<Container> it = containers.iterator();it.hasNext() && !found;) {
			Container container = it.next();
			
			// The creatormanager holds the list of beans
			CreatorManager ctManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
			if( null != ctManager ) {
				// The remoter builds interface scripts. 
				Remoter remoter = (Remoter) container.getBean(Remoter.class.getName());
				String path = getPathReplacementString(container);
				try {
					String script = remoter.generateInterfaceScript(scriptName, path);
					found = true;
					// Must remove the engine init script to avoid unneeded duplication
					script = removeEngineInit(script);
					sb.append(script);
				}
				catch(SecurityException ex){throw new BundlingProcessException(ex); }
			}
		}
		if(!found)
			throw new IllegalArgumentException("The DWR bean named '" + scriptName + "' was not found in any DWR configuration instance."); 
		
		return sb;
	}
940605
public ExecuteSQLQueryBuilder validateScript(Resource scriptResource, String type) {
        return validateScript(scriptResource, type, FileUtils.getDefaultCharset());
    }
1057054
public void eInit(SarlScript script, String name, IJvmTypeProvider context) {
		setTypeResolutionContext(context);
		if (this.sarlEnumeration == null) {
			this.container = script;
			this.sarlEnumeration = SarlFactory.eINSTANCE.createSarlEnumeration();
			script.getXtendTypes().add(this.sarlEnumeration);
			this.sarlEnumeration.setAnnotationInfo(XtendFactory.eINSTANCE.createXtendTypeDeclaration());
			if (!Strings.isEmpty(name)) {
				this.sarlEnumeration.setName(name);
			}
		}
	}
1334793
@CallMethod(pattern = "install/version/script")
    public void addScript(@CallParam(pattern = "install/version/script") final String _code,
                          @CallParam(pattern = "install/version/script", attributeName = "type") final String _type,
                          @CallParam(pattern = "install/version/script", attributeName = "name") final String _name,
                          @CallParam(pattern = "install/version/script", attributeName = "function")
                            final String _function)
    {
        AbstractScript script = null;
        if ("rhino".equalsIgnoreCase(_type)) {
            script = new RhinoScript(_code, _name, _function);
        } else if ("groovy".equalsIgnoreCase(_type)) {
            script = new GroovyScript(_code, _name, _function);
        }
        if (script != null) {
            this.scripts.add(script);
        }
    }
333125
@SuppressWarnings("squid:S1166") //For the UnsupportedOperationException
    private Script build(CharStream cs) throws ScriptBuilderException {

        Script v = new Script();

        ANTLRBtrplaceSL2Lexer lexer = new ANTLRBtrplaceSL2Lexer(cs);

        ErrorReporter errorReporter = errBuilder.build(v);

        lexer.setErrorReporter(errorReporter);
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        ANTLRBtrplaceSL2Parser parser = new ANTLRBtrplaceSL2Parser(tokens);
        parser.setErrorReporter(errorReporter);

        SymbolsTable t = new SymbolsTable();

        parser.setTreeAdaptor(new BtrPlaceTreeAdaptor(v, model, namingServiceNodes, namingServiceVMs, tpls, errorReporter, t, includes, catalog));

        try {
            BtrPlaceTree tree = (BtrPlaceTree) parser.script_decl().getTree();
            if (tree != null) {
                if (tree.token != null) {
                        tree.go(tree); //Single instruction
                } else {
                    for (int i = 0; i < tree.getChildCount(); i++) {
                            tree.getChild(i).go(tree);
                        }
                    }
            }
        } catch (RecognitionException e) {
            throw new ScriptBuilderException(e.getMessage(), e);
        } catch (UnsupportedOperationException e) {
            //We only keep the error message
            errorReporter.append(0, 0, e.getMessage());
        }
        if (!errorReporter.getErrors().isEmpty()) {
            throw new ScriptBuilderException(errorReporter);
        }
        return v;
    }
823913
protected Scriptable loadConfig(String configScript) throws IOException {
		configScript = processConfig(configScript);
		Context cx = Context.enter();
		Scriptable config;
		try {
			sharedScope = cx.initStandardObjects(null, true);

			// set up options object
			IOptions options = aggregator.getOptions();
			if (options != null) {
				optionsUpdated(options, 1);
			}
			// set up init params object
			InitParams initParams = aggregator.getInitParams();
			if (initParams != null) {
				Scriptable jsInitParams = cx.newObject(sharedScope);
				Collection<String> names = initParams.getNames();
				for (String name : names) {
					Collection<String> values = initParams.getValues(name);
					Object value = Context.javaToJS(values.toArray(new String[values.size()]), sharedScope);
					ScriptableObject.putProperty(jsInitParams, name, value);
				}
				ScriptableObject.putProperty(sharedScope, "initParams", jsInitParams); //$NON-NLS-1$
			}

			// set up bundle manifest headers property
			if ( aggregator.getPlatformServices() != null) {
				if( aggregator.getPlatformServices().getHeaders() != null){
					Dictionary<String, String> headers = (Dictionary<String, String>)( aggregator.getPlatformServices().getHeaders());
					Scriptable jsHeaders = cx.newObject(sharedScope);
					Enumeration<String> keys = headers.keys();
					while (keys.hasMoreElements()) {
						String key = keys.nextElement();
						Object value = Context.javaToJS(headers.get(key), sharedScope);
						ScriptableObject.putProperty(jsHeaders, key, value);
					}
					ScriptableObject.putProperty(sharedScope, "headers", jsHeaders); //$NON-NLS-1$
				}
			}

			// set up console object
			Console console = newConsole();
			Object jsConsole = Context.javaToJS(console, sharedScope);
			ScriptableObject.putProperty(sharedScope, "console", jsConsole); //$NON-NLS-1$
			GetPropertyFunction getPropertyFn = newGetPropertyFunction(sharedScope, aggregator);
			ScriptableObject.putProperty(sharedScope, "getProperty", getPropertyFn); //$NON-NLS-1$

			// Call the registered scope modifiers
			callConfigScopeModifiers(sharedScope);

			cx.evaluateString(sharedScope, "var config = " +  //$NON-NLS-1$
					aggregator.substituteProps(configScript, new IAggregator.SubstitutionTransformer() {
						@Override
						public String transform(String name, String value) {
							// escape forward slashes for javascript literals
							return value.replace("\\", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$
						}
					}), getConfigUri().toString(), 1, null);
			config = (Scriptable)sharedScope.get("config", sharedScope); //$NON-NLS-1$
			if (config == Scriptable.NOT_FOUND) {
				throw new IllegalStateException("config is not defined."); //$NON-NLS-1$
			}
		} finally {
			Context.exit();
		}
		return config;
	}
819342
public static List<SqlScriptSource> classPathScripts(final String pattern) {
        List<SqlScriptSource> results = new ArrayList<>();

        String[] parts = pattern.split("/");
        String path = join(asList(copyOfRange(parts, 0, parts.length - 1)), "/");
        String normalizedPath = path.startsWith("/") ? path : format("/%s", path);

        URL baseFolder = ScriptResolver.class.getResource(normalizedPath);

        if (baseFolder == null)
            throw new ScriptResolutionException(normalizedPath);

        if (baseFolder.getProtocol().equals("jar")) {
            String normalizedPattern = pattern.startsWith("/") ? pattern : format("/%s", pattern);
            String regexPattern = normalizedPattern.replace("*", ".*");
            String jarPath = baseFolder.getPath().substring(5, baseFolder.getPath().indexOf("!"));
            JarFile jar;

            try {
                jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            Enumeration<JarEntry> entries = jar.entries();
            List<String> names = new ArrayList<>();
            while (entries.hasMoreElements()) {
                String name = "/" + entries.nextElement().getName();
                if (name.matches(regexPattern)) {
                    names.add(name);
                }
            }
            Collections.sort(names);
            for (String found : names) {
                results.add(classPathScript(found));
            }
        } else {
            FileFilter filter = new WildcardFileFilter(parts[parts.length - 1]);
            List<File> filesInPath = asList(asFile(baseFolder).listFiles(filter));
            Collections.sort(filesInPath);
            for (File f : filesInPath) {
                results.add(Sources.fromFile(f));
            }
        }

        return results;
    }
1259553
Object executeScript(String jsScript, Map<String, Object> parameters) {
    EntityType entityType = entityTypeFactory.create("entity");
    Set<String> attributeNames = parameters.keySet();
    attributeNames.forEach(key -> entityType.addAttribute(attributeFactory.create().setName(key)));
    if (attributeNames.iterator().hasNext()) {
      entityType.getAttribute(attributeNames.iterator().next()).setIdAttribute(true);
    }
    Entity entity = new DynamicEntity(entityType);
    parameters.forEach(entity::set);
    return jsMagmaScriptEvaluator.eval(jsScript, entity);
  }
1342810
public static ExecutableScript parseCamundaScript(Element scriptElement) {
    String scriptLanguage = scriptElement.attribute("scriptFormat");
    if (scriptLanguage == null || scriptLanguage.isEmpty()) {
      throw new BpmnParseException("Missing attribute 'scriptFormatAttribute' for 'script' element", scriptElement);
    }
    else {
      String scriptResource = scriptElement.attribute("resource");
      String scriptSource = scriptElement.getText();
      try {
        return ScriptUtil.getScript(scriptLanguage, scriptSource, scriptResource, getExpressionManager());
      }
      catch (ProcessEngineException e) {
        throw new BpmnParseException("Unable to process script", scriptElement, e);
      }
    }
  }
1078866
protected void executeScript(String scriptPath) {
        URL scriptUrl = null;
        try {
            if (scriptPath.startsWith("classpath:")) {
                String script = scriptPath.substring("classpath:".length());
                scriptUrl = ClassUtil.getResource(script);
                if (scriptUrl == null) {
                    log.warn("Script '{}' not found!", scriptPath);
                }
            } else {
                File file = new File(scriptPath);
                if (file.exists()) {
                    scriptUrl = file.toURI().toURL();
                } else {
                    log.warn("Script '{}' not found!", scriptPath);
                }
            }

            // execute the script
            if (scriptUrl != null) {
                executeScript(scriptUrl);
            }

        } catch (Exception e) {
            log.error("Failed to parse '{}' as a url", scriptPath);
        }
    }
1154943
protected final void registStaticScript(Class<? extends T> scriptClass)
	{
		try {
			boolean isAbstractOrInterface = Modifier.isAbstract(scriptClass.getModifiers())
					|| Modifier.isInterface(scriptClass.getModifiers());// 是否是抽象类
			if(isAbstractOrInterface)
			{
				throw new UnsupportedOperationException(scriptClass +"can not newInstance");
			}
			T script = scriptClass.newInstance();
			int code=script.getMessageCode();
			Class<? extends T> old=staticCodeMap.get(code);
			staticCodeMap.put(code,scriptClass);
			if(old==null)
			{
				_log.info("regist Static codeScript,code="+code+"(0x"+Integer.toHexString(code)+"),class="+scriptClass);
			}else
			{
				_log.info("regist Static codeScript,code="+code+"(0x"+Integer.toHexString(code)+"),class="+scriptClass+",Override script="+old);
			}
		} catch (Exception e) {
			_log.error(e.getMessage(),e);
		}
	}
26921
public List<V> executeModules(List<ScriptModule> modules, ScriptModuleExecutable<V> executable) {
        Objects.requireNonNull(modules, "modules");
        Objects.requireNonNull(executable, "executable");

        List<Future<V>> futureResults = new ArrayList<Future<V>>(modules.size());
        for (ScriptModule module : modules) {
           Future<V> future = new ScriptModuleExecutionCommand<V>(executorId, executable, module).queue();
           futureResults.add(future);

           ExecutionStatistics moduleStats = getOrCreateModuleStatistics(module.getModuleId());
           moduleStats.executionCount.incrementAndGet();
           moduleStats.lastExecutionTime.set(System.currentTimeMillis());
        }

        List<V> results = new ArrayList<V>(modules.size());
        for (int i = 0; i < futureResults.size(); i++) {
            Future<V> futureResult = futureResults.get(i);
            try {
                V result = futureResult.get();
                results.add(result);
            } catch (Exception e) {
                // the exception is already logged by the hystrix command, so just add some additional context
                ScriptModule failedModule = modules.get(i);
                logger.error("moduleId {} with creationTime: {} failed execution. see hystrix command log for deatils.",
                    failedModule.getModuleId(), failedModule.getCreateTime());
                continue;
            }
        }
        return results;
    }
616835
@Override
	public StringBuffer getClientSideHandlerScript(HttpServletRequest request) {

		StringBuffer sb = getHeaderSection(request);

		boolean useGzip = RendererRequestUtils.isRequestGzippable(request, this.config);

		Map<String, String> variants = this.config.getGeneratorRegistry().resolveVariants(request);
		sb.append("JAWR.loader.mapping='").append(getPathPrefix(request, this.config)).append("';\n");

		// Start an self executing function
		sb.append("(function(){\n");

		// shorthand for creating ResourceBundles. makes the script shorter.
		sb.append("function r(n, p, i,ie,aU){return new JAWR.ResourceBundle(n, p, i,ie,aU);}\n");

		sb.append("JAWR.loader.jsbundles = [");
		sb.append(getClientSideBundles(variants, useGzip));
		sb.append("]\n");

		// Retrieve the resourcehandler for CSS if there is one.
		ResourceBundlesHandler rsHandler = (ResourceBundlesHandler) request.getSession().getServletContext()
				.getAttribute(JawrConstant.CSS_CONTEXT_ATTRIBUTE);
		boolean isCSSHandler = false;
		if (null != rsHandler) {
			ClientSideHandlerGenerator generator = rsHandler.getClientSideHandler();
			// If this is not a pointer to the same generator it means this
			// generator is the javascript one,
			// so we add CSS bundles to the script
			if (this != generator) {
				variants = rsHandler.getConfig().getGeneratorRegistry().resolveVariants(request);
				sb.append(";JAWR.loader.cssbundles = [");
				sb.append(generator.getClientSideBundles(variants, useGzip));
				sb.append("];\n");
			} else
				isCSSHandler = true;

			// Add the mapping for css resources
			sb.append("JAWR.loader.cssmapping='").append(getPathPrefix(request, rsHandler.getConfig())).append("';\n");
		}
		// End self executing function
		sb.append("})();");

		// Appends extra functions for debug mode
		if (this.config.isDebugModeOn()) {
			sb.append(debugScriptTemplate.toString()).append("\n");
		}

		// The global bundles are already sorted and filtered by the
		// bundleshandler
		for (JoinableResourceBundle bundle : globalBundles) {
			String func = isCSSHandler ? "JAWR.loader.style(" : "JAWR.loader.script(";
			sb.append(func).append(JavascriptStringUtil.quote(bundle.getId())).append(");\n");
		}

		// Minify the result
		if (!this.config.isDebugModeOn()) {
			JSMinPostProcessor p = new JSMinPostProcessor();
			try {
				sb = p.minifyStringBuffer(sb, config.getResourceCharset());
			} catch (IOException | JSMin.JSMinException e) {
				throw new BundlingProcessException("Unexpected error creating client side resource handler", e);
			}
		}
		return sb;
	}
503615
public ScriptResult runScript(String scriptName, Map<String, Object> parameters) {
    Script script =
        dataService.query(SCRIPT, Script.class).eq(ScriptMetadata.NAME, scriptName).findOne();
    if (script == null) {
      throw new UnknownEntityException(SCRIPT, scriptName);
    }

    if (script.getParameters() != null) {
      for (ScriptParameter param : script.getParameters()) {
        if (!parameters.containsKey(param.getName())) {
          throw new GenerateScriptException("Missing parameter [" + param + "]");
        }
      }
    }

    Map<String, Object> scriptParameters = new HashMap<>(parameters);
    if (script.isGenerateToken()) {
      String token =
          tokenService.generateAndStoreToken(
              SecurityUtils.getCurrentUsername(), "For script " + script.getName());
      scriptParameters.put("molgenisToken", token);
    }

    ScriptRunner scriptRunner =
        scriptRunnerFactory.getScriptRunner(script.getScriptType().getName());

    FileMeta fileMeta = null;
    if (scriptRunner.hasFileOutput(script)) {
      String name = generateRandomString();
      String resultFileExtension = script.getResultFileExtension();
      if (resultFileExtension != null) {
        name += "." + script.getResultFileExtension();
      }
      File file = fileStore.getFileUnchecked(name);
      scriptParameters.put("outputFile", file.getAbsolutePath());
      fileMeta = createFileMeta(name, file);
      dataService.add(FILE_META, fileMeta);
    }
    String output = scriptRunner.runScript(script, scriptParameters);

    return new ScriptResult(fileMeta, output);
  }