Get a specific interface script

@param scriptName
The name of the script
@param context
The GeneratorContext
@return The script as a String
@throws IOException
16226
private String getInterfaceScript(String scriptName,
			final GeneratorContext context) throws IOException {
		Container container = getContainer(context);
		CreatorManager ctManager = (CreatorManager) container
				.getBean(CreatorManager.class.getName());
		if (ctManager.getCreator(scriptName, false) != null) {
			InterfaceHandler handler = (InterfaceHandler) ContainerUtil
					.getHandlerForUrlProperty(container, INTERFACE_HANDLER_URL);
			return handler.generateInterfaceScript(context.getServletContext()
					.getContextPath(), context.getConfig().getDwrMapping(),
					scriptName);
		} else
			throw new IllegalArgumentException("The DWR bean named '"
					+ scriptName
					+ "' was not found in any DWR configuration instance.");
	}
413169
private String executeScript(Run<?, ?> build, FilePath workspace, TaskListener listener, InputStream scriptStream)
            throws IOException {
        String result = "";
        Map binding = new HashMap<>();
        ExtendedEmailPublisherDescriptor descriptor = Jenkins.getActiveInstance().getDescriptorByType(ExtendedEmailPublisherDescriptor.class);
        Item parent = build.getParent();

        binding.put("build", build);
        binding.put("it", new ScriptContentBuildWrapper(build));
        binding.put("project", parent);
        binding.put("rooturl", descriptor.getHudsonUrl());
        binding.put("workspace", workspace);
        PrintStream logger = listener.getLogger();
        binding.put("logger", logger);

        String scriptContent = IOUtils.toString(scriptStream, descriptor.getCharset());

        if (scriptStream instanceof UserProvidedContentInputStream) {
            ScriptApproval.get().configuring(scriptContent, GroovyLanguage.get(), ApprovalContext.create().withItem(parent));
        }

        if (scriptStream instanceof UserProvidedContentInputStream && !AbstractEvalContent.isApprovedScript(scriptContent, GroovyLanguage.get())) {
            //Unapproved script, run it in the sandbox
            GroovyShell shell = createEngine(descriptor, binding, true);
            Object res = GroovySandbox.run(shell, scriptContent, new ProxyWhitelist(
                    Whitelist.all(),
                    new PrintStreamInstanceWhitelist(logger),
                    new EmailExtScriptTokenMacroWhitelist()

            ));
            if (res != null) {
                result = res.toString();
            }
        } else {
            if (scriptStream instanceof UserProvidedContentInputStream) {
                ScriptApproval.get().using(scriptContent, GroovyLanguage.get());
            }
            //Pre approved script, so run as is
            GroovyShell shell = createEngine(descriptor, binding, false);
            Script script = shell.parse(scriptContent);
            Object res = script.run();
            if (res != null) {
                result = res.toString();
            }
        }

        return result;
    }
552277
@RequestMapping(value = "/api/scripts/{scriptIdentifier}", method = RequestMethod.POST)
    public
    @ResponseBody
    Script updateScript(Model model, @PathVariable String scriptIdentifier,
                        @RequestParam(required = false) String name,
                        @RequestParam(required = false) String script) throws Exception {
        int scriptId = Integer.parseInt(scriptIdentifier);

        if (name != null) {
            ScriptService.getInstance().updateName(scriptId, name);
        }

        if (script != null) {
            ScriptService.getInstance().updateScript(scriptId, script);
        }

        return ScriptService.getInstance().getScript(scriptId);
    }
911085
private String loadScript() throws CmdLineException, IOException, InterruptedException {
        if(script==null)
            throw new CmdLineException(null, "No script is specified");
        if (script.equals("="))
            return IOUtils.toString(stdin);

        checkChannel();
        return null; // never called
    }
577006
private Object getScriptResult(String script, ScriptEngine engine) throws ScriptException {
        String scriptToExecute = script.substring(script.indexOf(":") + 1);
        return engine.eval(scriptToExecute);
    }
805876
public Script getScript(int id) {
        PreparedStatement statement = null;
        ResultSet results = null;

        try (Connection sqlConnection = SQLService.getInstance().getConnection()) {
            statement = sqlConnection.prepareStatement(
                "SELECT * FROM " + Constants.DB_TABLE_SCRIPT +
                    " WHERE id = ?"
            );
            statement.setInt(1, id);
            results = statement.executeQuery();
            if (results.next()) {
                return scriptFromSQLResult(results);
            }
        } catch (Exception e) {

        } finally {
            try {
                if (results != null) {
                    results.close();
                }
            } catch (Exception e) {
            }
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (Exception e) {
            }
        }

        return null;
    }
165461
private ScriptEngine getScriptEngine(String value) {
        String engineName = value.substring(0, value.indexOf(":"));
        if (engines.containsKey(engineName)) {
            return engines.get(engineName);
        } else {
            ScriptEngine engine = manager.getEngineByName(engineName);
            if (engine != null) {
                engines.put(engineName, engine);
            } else {
                log.warning(String.format("Could not find script engine by name '%s'", engineName));
            }
            return engine;
        }
    }
871957
public void eInit(SarlScript script, String name, IJvmTypeProvider context) {
		setTypeResolutionContext(context);
		if (this.sarlArtifact == null) {
			this.sarlArtifact = SarlFactory.eINSTANCE.createSarlArtifact();
			script.getXtendTypes().add(this.sarlArtifact);
			this.sarlArtifact.setAnnotationInfo(XtendFactory.eINSTANCE.createXtendTypeDeclaration());
			if (!Strings.isEmpty(name)) {
				this.sarlArtifact.setName(name);
			}
		}
	}
1042747
public static String readScript(final String resourceName) throws IOException {
        final StringBuilder buf = new StringBuilder();
        try (final InputStream inputStream = ScriptUtils.class.getResourceAsStream(resourceName)) {
            if (inputStream == null) {
                throw new IOException("Could not find script resource: " + resourceName);
            }
            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                String prefix = "";
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.length() > 0) {
                        buf.append(prefix).append(line.trim());
                        prefix = "\n";
                    }
                }
            }
        }
        return buf.toString();
    }
1295984
public void eInit(SarlScript script, String name, IJvmTypeProvider context) {
		setTypeResolutionContext(context);
		if (this.sarlSpace == null) {
			this.sarlSpace = SarlFactory.eINSTANCE.createSarlSpace();
			script.getXtendTypes().add(this.sarlSpace);
			this.sarlSpace.setAnnotationInfo(XtendFactory.eINSTANCE.createXtendTypeDeclaration());
			if (!Strings.isEmpty(name)) {
				this.sarlSpace.setName(name);
			}
		}
	}
966281
public static String getScriptEngineName(String filename) {
        String extension = FilenameUtils.getExtension(filename);
        if (StringUtils.isBlank(extension)) {
            logger.warn("Can't determine engine name based on filename without extension {}",filename);
            return null;
        }
        ScriptEngineManager manager = new ScriptEngineManager();
        List<ScriptEngineFactory> engines = manager.getEngineFactories();
        for (ScriptEngineFactory engineFactory : engines) {
            List<String> extensions = engineFactory.getExtensions();
            for (String supportedExt : extensions) {
                if (extension.equals(supportedExt)) {
                    // return first short name
                    return engineFactory.getNames().get(0);
                }
            }
        }
        logger.warn("Can't determine engine name based on filename and available script engines {}",filename);
        return null;
    }
1248619
private ScriptPluginProvider getPlugin(
            final PluginMeta pluginMeta,
            final File file,
            final ProviderDef pluginDef,
            final ProviderIdent ident
    ) throws
            ProviderLoaderException, PluginException
    {
        if (null == fileExpandedDir) {
            final File dir;
            try {
                dir = expandScriptPlugin(file);
            } catch (IOException e) {
                throw new ProviderLoaderException(e, ident.getService(), ident.getProviderName());
            }
            fileExpandedDir = dir;
            if (pluginDef.getPluginType().equals("script")) {

                final File script = new File(fileExpandedDir, pluginDef.getScriptFile());
                //set executable bit for script-file of the provider
                try {
                    ScriptfileUtils.setExecutePermissions(script);
                } catch (IOException e) {
                    log.warn("Unable to set executable bit for script file: " + script + ": " + e.getMessage());
                }
            }
            debug("expanded plugin dir! " + fileExpandedDir);
        } else {
            debug("expanded plugin dir: " + fileExpandedDir);
        }
        if (pluginDef.getPluginType().equals("script")) {
            final File script = new File(fileExpandedDir, pluginDef.getScriptFile());
            if (!script.exists() || !script.isFile()) {
                throw new PluginException("Script file was not found: " + script.getAbsolutePath());
            }
        }
        return new ScriptPluginProviderImpl(pluginMeta, pluginDef, file, fileExpandedDir);
    }
418568
private ScriptValidationContext getScriptValidationContext(Element messageElement, String messageType) {
        ScriptValidationContext context = null;

        boolean done = false;
        List<?> validateElements = DomUtils.getChildElementsByTagName(messageElement, "validate");
        if (validateElements.size() > 0) {
            for (Iterator<?> iter = validateElements.iterator(); iter.hasNext();) {
                Element validateElement = (Element) iter.next();

                Element scriptElement = DomUtils.getChildElementByTagName(validateElement, "script");

                // check for nested validate script child node
                if (scriptElement != null) {
                    if (!done) {
                        done = true;
                    } else {
                        throw new BeanCreationException("Found multiple validation script definitions - " +
                                "only supporting a single validation script for message validation");
                    }

                    context = new ScriptValidationContext(messageType);
                    String type = scriptElement.getAttribute("type");
                    context.setScriptType(type);

                    String filePath = scriptElement.getAttribute("file");
                    if (StringUtils.hasText(filePath)) {
                        context.setValidationScriptResourcePath(filePath);
                        if (scriptElement.hasAttribute("charset")) {
                            context.setValidationScriptResourceCharset(scriptElement.getAttribute("charset"));
                        }
                    } else {
                        context.setValidationScript(DomUtils.getTextValue(scriptElement));
                    }
                }
            }
        }

        return context;
    }
355382
public void eInit(SarlScript script, String name, IJvmTypeProvider context) {
		setTypeResolutionContext(context);
		if (this.sarlCapacity == null) {
			this.sarlCapacity = SarlFactory.eINSTANCE.createSarlCapacity();
			script.getXtendTypes().add(this.sarlCapacity);
			this.sarlCapacity.setAnnotationInfo(XtendFactory.eINSTANCE.createXtendTypeDeclaration());
			if (!Strings.isEmpty(name)) {
				this.sarlCapacity.setName(name);
			}
		}
	}
438451
@Override
    public Object get(final String varName) {
        return runWithContext(new RhinoCallable<Object, RuntimeException>() {
            @Override
            protected Object doCall(Context cx, Scriptable scope) {
                return unwrappedValue(scope.get(varName, scope));
            }
        });
    }
495906
protected void generateScriptSourceAppender() {
		final List<StringConcatenationClient> topElements = generateTopElements(false, true);
		final TypeReference appender = getCodeElementExtractor().getElementAppenderImpl("Script"); //$NON-NLS-1$
		final StringConcatenationClient content = new StringConcatenationClient() {
			@Override
			protected void appendTo(TargetStringConcatenation it) {
				it.append("/** Appender of " + getLanguageName() + " scripts."); //$NON-NLS-1$ //$NON-NLS-2$
				it.newLine();
				it.append(" *"); //$NON-NLS-1$
				it.newLine();
				it.append(" */"); //$NON-NLS-1$
				it.newLine();
				it.append("@SuppressWarnings(\"all\")"); //$NON-NLS-1$
				it.newLine();
				it.append("public class "); //$NON-NLS-1$
				it.append(getScriptAppender().getSimpleName());
				it.append(" extends "); //$NON-NLS-1$
				it.append(getCodeElementExtractor().getAbstractAppenderImpl());
				it.append(" implements "); //$NON-NLS-1$
				it.append(getScriptBuilderInterface());
				it.append(" {"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
				it.append(generateFieldsAndMethods(false, true));
				for (final StringConcatenationClient element : topElements) {
					it.append(element);
				}
				it.append("}"); //$NON-NLS-1$
				it.newLineIfNotEmpty();
				it.newLine();
			}

		};
		final JavaFileAccess javaFile = getFileAccessFactory().createJavaFile(appender, content);
		javaFile.writeTo(getSrcGen());
	}
865906
private static String addScriptDirectives(Element scriptElement) throws IOException, DocumentTemplateException {
    String scriptReplacement = "";

    List scriptParts = parseScriptParts(scriptElement.getValue());
    for (int index = 0; index < scriptParts.size(); index++) {
      ScriptPart scriptPart = (ScriptPart) scriptParts.get(index);
      if (scriptPart.getLocation() == null) {
        scriptReplacement = scriptPart.getText();
      }
      else {
        Element enclosingElement = findEnclosingElement(scriptElement, scriptPart.getLocation());
        if (scriptPart.isTagAttribute()) {
          String[] nameValue = scriptPart.getText().split("=", 2);
          if (nameValue.length != 2) {
            throw new DocumentTemplateException("script error: # attribute name=value not found");
          }

          String attributeNamespace = enclosingElement.getNamespaceURI();
          if (nameValue[0].contains(":")) {
            String prefix = nameValue[0].split(":")[0];
            if (!prefix.equals(enclosingElement.getNamespacePrefix())) {
              attributeNamespace = XPATH_CONTEXT.lookup(prefix);
              if (attributeNamespace == null) {
                throw new DocumentTemplateException("unsupported attribute namespace: " + prefix);
              }
            }
          }

          enclosingElement.addAttribute(new Attribute(nameValue[0], attributeNamespace, nameValue[1]));
        }
        else {
          ParentNode parent = enclosingElement.getParent();
          int parentIndex = parent.indexOf(enclosingElement);
          if (scriptPart.afterEndTag()) {
            parentIndex++;
          }
          parent.insertChild(newNode(scriptPart.getText()), parentIndex);
        }
      }
    }

    return scriptReplacement;
  }