/*
(non-Javadoc)
@see net.roboconf.dm.rest.services.internal.resources.IManagementResource
#loadUnzippedApplicationTemplate(java.lang.String)
347522
@Override
	public Response loadUnzippedApplicationTemplate( String localFilePath ) {

		if( localFilePath == null )
			localFilePath = "null";

		this.logger.fine( "Request: load application from a local file (" + localFilePath + ")." );
		Response response;
		try {
			ApplicationTemplate tpl = this.manager.applicationTemplateMngr().loadApplicationTemplate( new File( localFilePath ));
			response = Response.ok().entity( tpl ).build();

		} catch( AlreadyExistingException e ) {
			response = handleError(
					Status.FORBIDDEN,
					new RestError( REST_MNGMT_CONFLICT, e ),
					lang( this.manager )).build();

		} catch( InvalidApplicationException e ) {
			response = handleError(
					Status.NOT_ACCEPTABLE,
					new RestError( REST_MNGMT_INVALID_TPL, e ),
					lang( this.manager )).build();

		} catch( IOException e ) {
			response = handleError(
					Status.UNAUTHORIZED,
					new RestError( REST_SAVE_ERROR, e ),
					lang( this.manager )).build();

		} catch( UnauthorizedActionException e ) {
			response = handleError(
					Status.CONFLICT,
					new RestError( REST_MNGMT_CONFLICT, e ),
					lang( this.manager )).build();
		}

		return response;
	}
1062295
@SuppressWarnings("unchecked")
    @Override
    public void addWebApplication(DeployedModule deployedModule, List extensionFactories) throws WebAppNotLoadedException {
       
        com.ibm.ws.webcontainer.osgi.container.DeployedModule deployedModuleImpl = (com.ibm.ws.webcontainer.osgi.container.DeployedModule) deployedModule;
        String ct = deployedModuleImpl.getProperContextRoot();
        String contextRoot = deployedModuleImpl.getMappingContextRoot();

        String displayName = deployedModule.getDisplayName();
        
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
            logger.logp(Level.FINE, CLASS_NAME,"addWebApplication",  "enter ["+ displayName +"]");
        }


        WebGroup webGroup = (WebGroup) requestMapper.map(contextRoot);

        if (webGroup != null && ct.equalsIgnoreCase(webGroup.getConfiguration().getContextRoot())) {
            // begin 296368 Nested exceptions lost for problems during
            // application startup WAS.webcontainer
            List list = webGroup.getWebApps();
            String originalName = "";
            if (list != null && (list.size() > 0)) {
                WebApp originalWebApp = (WebApp) list.get(0);
                originalName = originalWebApp.getWebAppName();
            }
            logger.logp(Level.SEVERE, CLASS_NAME, "addWebApplication", "context.root.already.in.use", new Object[] { displayName, contextRoot, originalName, displayName });
            throw new WebAppNotLoadedException("Context root " + contextRoot + " is already bound. Cannot start application " + displayName);
            // end 296368 Nested exceptions lost for problems during application
            // startup WAS.webcontainer
        }
        // The following is used by/for Liberty: requred to create the webgroup & 
        // webgroup configuration
        webGroup = new WebGroup(contextRoot, this);
        WebGroupConfiguration wgConfig = new WebGroupConfiguration(deployedModule.getName());
        wgConfig.setContextRoot(deployedModule.getContextRoot());
        wgConfig.setVersionID(deployedModule.getWebAppConfig().getVersion());
        // begin LIDB2356.1: WebContainer work for incorporating SIP

        // Liberty: if this is one of the "new" WebAppConfiguration objects,
        // add this as the virtual host for better delegation (and less object copying)
        com.ibm.ws.webcontainer.webapp.WebAppConfiguration baseAppConfig = deployedModule.getWebAppConfig();
        try {
            ((com.ibm.ws.webcontainer.osgi.webapp.WebAppConfiguration) baseAppConfig).setVirtualHost(this);
        } catch (ClassCastException cce) {
            baseAppConfig.setVirtualHostName(getName());
        }

        wgConfig.setWebAppHost(this);
        // end LIDB2356.1: WebContainer work for incorporating SIP
        webGroup.initialize(wgConfig);
        try {
            webGroup.addWebApplication(deployedModule, extensionFactories);
            Object[] args = { displayName, vHostConfig.toString() };
            logger.logp(Level.INFO, CLASS_NAME, "addWebApplication", "module.[{0}].successfully.bound.to.virtualhost.[{1}]", args);
        } catch (Throwable t) {
            //PI58875
            if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){
                logger.logp(Level.FINE, CLASS_NAME,"addWebApplication",  "error adding web app ["+ displayName +"]");
            }
            webGroup.destroy();  //preventing the classLoader memory leak
            webGroup = null;
            //PI58875 end 

            // requestMapper.removeMapping(contextRoot);
            // Do not need to remove mapping because we wait until we're sure we should add it!
            // PK67698 removeMapping(contextRoot);
            // 296368 added rootCause to newly created exception.
            throw new WebAppNotLoadedException(t.getMessage(), t);
        }

        // PK67698 Start
        try {
            addMapping(contextRoot, webGroup);

            webGroup.notifyStart();
        } catch (Exception exc) {
            // begin 296368 Nested exceptions lost for problems during
            // application startup WAS.webcontainer
            if (TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINE)) {
                logger.logp(Level.FINE, CLASS_NAME, "addWebApplication", "error adding mapping ", exc); /* @283348.1 */
            }
            webGroup.destroy();
            throw new WebAppNotLoadedException("Context root " + contextRoot + " mapping unable to be bound. Application " + displayName + " unavailable.", exc);
            // end 296368 Nested exceptions lost for problems during application
            // startup WAS.webcontainer
        }
        // PK67698 End
    }
459223
func LoadTemplate(path string) (*wfv1.Template, error) {
	var tmpl wfv1.Template
	err := unmarshalAnnotationField(path, common.AnnotationKeyTemplate, &tmpl)
	if err != nil {
		return nil, err
	}
	return &tmpl, nil
}
727823
public function load($template, $pkgHandle = null)
    {
        extract($this->data);

        if (file_exists(DIR_FILES_EMAIL_TEMPLATES . "/{$template}.php")) {
            include DIR_FILES_EMAIL_TEMPLATES . "/{$template}.php";
        } else {
            if ($pkgHandle != null) {
                if (is_dir(DIR_PACKAGES . '/' . $pkgHandle)) {
                    include DIR_PACKAGES . '/' . $pkgHandle . '/' . DIRNAME_MAIL_TEMPLATES . "/{$template}.php";
                } else {
                    include DIR_PACKAGES_CORE . '/' . $pkgHandle . '/' . DIRNAME_MAIL_TEMPLATES . "/{$template}.php";
                }
            } else {
                include DIR_FILES_EMAIL_TEMPLATES_CORE . "/{$template}.php";
            }
        }

        if (isset($from) && is_array($from) && isset($from[0])) {
            $this->from($from[0], isset($from[1]) ? $from[1] : null);
        }
        $this->template = $template;
        $this->subject = $subject;
        $this->body = (isset($body) && is_string($body)) ? $body : false;
        $this->bodyHTML = (isset($bodyHTML) && is_string($bodyHTML)) ? $bodyHTML : false;
    }
1271649
private void initIndex() throws Exception {

        //0. Add the tasklog template
        if (doesResourceNotExist("/_template/tasklog_template")) {
            logger.info("Creating the index template 'tasklog_template'");
            InputStream stream = ElasticSearchDAOV5.class.getResourceAsStream("/template_tasklog.json");
            byte[] templateSource = IOUtils.toByteArray(stream);

            HttpEntity entity = new NByteArrayEntity(templateSource, ContentType.APPLICATION_JSON);
            try {
                elasticSearchAdminClient.performRequest(HttpMethod.PUT, "/_template/tasklog_template", Collections.emptyMap(), entity);
            } catch (IOException e) {
                logger.error("Failed to initialize tasklog_template", e);
            }
        }
    }
271199
public TemplateCompilationResults reloadContextAndTemplates(boolean all)
        throws Exception {

        // Create the new merged context source
        TeaServletContextSource contextSource =
            new TeaServletContextSource(
                mApplicationDepot.getClass().getClassLoader(),
                mApplicationDepot,
                getServletContext(),
                getLog(),
                true,
                mProperties.getBoolean("management.httpcontext", false),
                mProperties.getInt("management.httpcontext.readUrlCacheSize", 500),
                isProfilingEnabled());

        // Create a new template source using the newly loaded context
        // source from the new application depot
        TeaServletTemplateSource templateSrc =
            createTemplateSource(contextSource);

        // Recompile all templates using the new context source
        TemplateCompilationResults results =
            templateSrc.compileTemplates(null, all);

        // The new context source and template source are ready for
        // use, set the member variables
        synchronized(this) {
            mApplicationDepot.setContextSource(contextSource);
            mTemplateSource = templateSrc;
        }

        // Return the compilation results
        return results;
    }
381328
public void invokeTemplate(int line, String name, ITemplate caller, ITag.__ParameterList params, ITag.__Body body, ITag.__Body context, boolean ignoreNonExistsTag) {
        if (_nonExistsTags.contains(name)) return;

        Sandbox.enterSafeZone(secureCode);
        RythmEvents.ENTER_INVOKE_TEMPLATE.trigger(this, (TemplateBase) caller);
        try {
            // try tag registry first
            ITemplate t = _tags.get(name);
            if (null == t) {
                t = _templates.get(name);
            }
            if (null == t && S.isEqual(name, caller.__getName())) {
                // is calling self
                t = caller;
            }

            if (null == t) {
                // try imported path
                TemplateClass tc = caller.__getTemplateClass(true);
                if (null != tc.importPaths) {
                    for (String s : tc.importPaths) {
                        if (s.startsWith("java")) {
                            continue;
                        }
                        String name0 = s + "." + name;
                        t = _tags.get(name0);
                        if (null == t) t = _templates.get(name0);
                        if (null != t) break;
                    }
                }

                // try relative path
                if (null == t) {
                    String callerName = tc.getTagName();
                    int pos = -1;
                    if (null != callerName) pos = callerName.lastIndexOf(".");
                    if (-1 != pos) {
                        String name0 = callerName.substring(0, pos) + "." + name;
                        t = _tags.get(name0);
                        if (null == t) t = _templates.get(name0);
                    }
                }

                // try load the tag from resource
                if (null == t) {
                    tc = resourceManager().tryLoadTemplate(name, tc, caller.__curCodeType());
                    if (null != tc) t = _templates.get(tc.getTagName());
                    if (null == t) {
                        if (ignoreNonExistsTag) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("cannot find tag: " + name);
                            }
                            _nonExistsTags.add(name);
                            if (isDevMode() && nonExistsTemplatesChecker == null) {
                                nonExistsTemplatesChecker = new NonExistsTemplatesChecker();
                            }
                            return;
                        } else {
                            throw new NullPointerException("cannot find tag: " + name);
                        }
                    }
                    t = t.__cloneMe(this, caller);
                }
            }

            if (!(t instanceof JavaTagBase)) {
                // try refresh the tag loaded from template file under tag root
                // note Java source tags are not reloaded here
                String cn = t.getClass().getName();
                TemplateClass tc0 = classes().getByClassName(cn);
                if (null == tc0) {
                    throw new NullPointerException(String.format("null tc0 found. t.class: %s, name: %s, caller.class: %s", cn, name, caller.getClass()));
                }
                t = tc0.asTemplate(caller, this);
            } else {
                t = t.__cloneMe(this, caller);
            }

            if (null != params) {
                if (t instanceof JavaTagBase) {
                    ((JavaTagBase) t).__setRenderArgs0(params);
                } else {
                    for (int i = 0; i < params.size(); ++i) {
                        ITag.__Parameter param = params.get(i);
                        if (null != param.name) t.__setRenderArg(param.name, param.value);
                        else t.__setRenderArg(i, param.value);
                    }
                }
            }
            if (null == body && null != params) {
                body = (ITag.__Body) params.getByName("__body");
                if (null == body) {
                    body = (ITag.__Body) params.getByName("_body");
                }
            }
            if (null != body) {
                t.__setRenderArg("__body", body);
                t.__setRenderArg("_body", body); // for compatibility
            }
            RythmEvents.ON_TAG_INVOCATION.trigger(this, F.T2((TemplateBase) caller, t));
            try {
                if (null != context) {
                    t.__setBodyContext(context);
                }
                t.__setSecureCode(secureCode).__call(line);
            } finally {
                RythmEvents.TAG_INVOKED.trigger(this, F.T2((TemplateBase) caller, t));
            }
        } finally {
            RythmEvents.EXIT_INVOKE_TEMPLATE.trigger(this, (TemplateBase) caller);
            Sandbox.leaveCurZone(secureCode);
        }
    }
1246286
@Override
	public Response bindApplication( String applicationName, String externalExportPrefix, String boundApp ) {

		this.logger.fine( "Binding " + boundApp  + " to the " + externalExportPrefix + " prefix in application " + applicationName + "." );
		String lang = lang( this.manager );
		Response response;
		try {
			ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName );
			if( ma == null ) {
				response = handleError(
						Status.NOT_FOUND,
						new RestError( REST_INEXISTING, application( applicationName )),
						lang ).build();

			} else {
				this.manager.applicationMngr().bindOrUnbindApplication( ma, externalExportPrefix, boundApp, true );
				response = Response.ok().build();
			}

		} catch( UnauthorizedActionException | IOException e ) {
			response = RestServicesUtils.handleError(
					Status.FORBIDDEN,
					new RestError( ErrorCode.REST_UNDETAILED_ERROR, e ),
					lang ).build();
		}

		return response;
	}
186128
public static Collection<TemplateEntry> findTemplatesForApplication( String appName, Collection<TemplateEntry> templates ) {

		final Collection<TemplateEntry> result = new ArrayList<> ();
		for( TemplateEntry te : templates ) {
			// TE.appName == null => OK. It applies to this application.
			// TE.appName == appName => OK. It also applies.
			if( te.getAppName() == null || te.getAppName().equals( appName ))
				result.add( te );
		}

		return result;
	}
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);
		}
	}
605875
public Response getTemplate(String id) throws RequestException, LocalOperationException {
        Request request = new Request(this);
        return new Response(request.get("/templates/" + id));
    }
1273527
public static void loadTemplate(SheetTemplate template, int sheetIndex) {

        if (sheetIndex < 0) sheetIndex = 0;
        template.sheetIndex = sheetIndex;
        template.sheet = template.workbook.getSheetAt(sheetIndex);
        initModuleConfig(template);
        template.currentRowIndex = template.initRowIndex;
        template.currentColumnIndex = template.initColumnIndex;
        template.lastRowIndex = template.sheet.getLastRowNum();
    }
1156275
private ConcurrentHashMap<String, String> load(final StringBuilder packageName, final File dir) throws IOException {
		LOG.debug("Loading SQL template.[{}]", packageName);

		ConcurrentHashMap<String, String> sqlMap = new ConcurrentHashMap<>();
		File[] files = dir.listFiles();
		for (File file : files) {
			String fileName = file.getName();
			if (file.isDirectory()) {
				sqlMap.putAll(load(makeNewPackageName(packageName, file), file));
			} else if (fileName.toLowerCase().endsWith(fileExtension)) {
				String sql = trimSlash(read(new BufferedReader(new InputStreamReader(new FileInputStream(file),
						getSqlEncoding()))));
				String sqlName = makeSqlName(packageName, fileName);
				sqlMap.put(sqlName, sql);

				LOG.trace("Loaded SQL template.[{}]", fileName);
				LOG.trace("Add SQL template.[{}],[{}]", sqlName, sql);
			}
		}
		return sqlMap;
	}
1347911
public static ApplicationTemplateDescriptor load( File f ) throws IOException {

		// Read the file's content
		String fileContent = Utils.readFileContent( f );
		Logger logger = Logger.getLogger( ApplicationTemplateDescriptor.class.getName());
		Properties properties = Utils.readPropertiesQuietly( fileContent, logger );
		if( properties.get( "fail.read" ) != null )
			throw new IOException( "This is for test purpose..." );

		ApplicationTemplateDescriptor result = load( properties );

		// Resolve line numbers then
		int lineNumber = 1;
		for( String line : fileContent.split( "\n" )) {

			for( String property : ALL_PROPERTIES ) {
				if( line.trim().matches( "(" + LEGACY_PREFIX + ")?" + property + "\\s*[:=].*" )) {
					result.propertyToLine.put( property, lineNumber );
					break;
				}
			}

			lineNumber ++;
		}

		return result;
	}
614722
public static AppMethodInfo[] getAppMethodsCalled(String basePath, final String templateName,
            final String contextClass) {

        final HashMap<AppMethodInfo, AppMethodInfo> methodsCalledMap =
            new HashMap<AppMethodInfo, AppMethodInfo>();

        try {
            File templatePath = new File(new File(basePath),
                templateName.replace('.', '/') + ".class");
            if (!templatePath.exists() &&
                    templateName.startsWith(TEMPLATE_PACKAGE)) {
                templatePath = new File(new File(basePath),
                    templateName.substring(TEMPLATE_PACKAGE.length()).
                    replace('.','/') + ".class");
            }

            final MethodInfo executeMethod = getTemplateExecuteMethod(new FileInputStream(templatePath));

            CodeDisassembler cd = new CodeDisassembler(executeMethod);
            cd.disassemble(new CodeAssemblerPrinter(executeMethod
                .getMethodDescriptor().getParameterTypes(), true, null) {

                 public void invokeVirtual(String className, String methodName,
                         TypeDesc ret, TypeDesc[] params)  {
                     if ("print".equals(methodName) ||
                             "toString".equals(methodName) ||
                             "equals".equals(methodName) ||
                             (contextClass.indexOf(className) == -1 &&
                             className.indexOf("MergedClass") == -1))
                         return;

                     AppMethodInfo ami = new AppMethodInfo(methodName, params);
                     if (! methodsCalledMap.containsKey(ami))
                         methodsCalledMap.put(ami, ami);
                     else
                         methodsCalledMap.get(ami).incCallCount();
                 }

                 public void println(String s) { } // Do nothing
            });

            final MethodInfo substituteMethod = getTemplateSubstituteMethod(new FileInputStream(templatePath));

            if (substituteMethod == null)
                return methodsCalledMap.values().toArray(
                    new AppMethodInfo[methodsCalledMap.values().size()]);

            // check the substitute methods on this template
            cd = new CodeDisassembler(substituteMethod);
            cd.disassemble(new CodeAssemblerPrinter(substituteMethod
                .getMethodDescriptor().getParameterTypes(), true, null) {

                 public void invokeVirtual(String className, String methodName,
                         TypeDesc ret, TypeDesc[] params)  {
                     if ("print".equals(methodName) ||
                             "toString".equals(methodName) ||
                             "equals".equals(methodName) ||
                             (contextClass.indexOf(className) == -1 &&
                             className.indexOf("MergedClass") == -1))
                         return;

                     AppMethodInfo ami = new AppMethodInfo(methodName, params);
                     if (! methodsCalledMap.containsKey(ami))
                         methodsCalledMap.put(ami, ami);
                     else
                         methodsCalledMap.get(ami).incCallCount();
                 }

                 public void println(String s) { } // Do nothing
            });
        }
        catch (IOException ix) {
            return new AppMethodInfo[0];
        }

        return methodsCalledMap.values().toArray(
            new AppMethodInfo[methodsCalledMap.values().size()]);
    }
550571
protected Map<String, String> prepareRequiredParameters(final FunctionTemplate template,
                                                            final BindingTemplate bindingTemplate)
        throws MojoFailureException {
        info("");
        info(PREPARE_PARAMS);

        prepareFunctionName();

        preparePackageName();

        final Map<String, String> params = new HashMap<>();
        params.put("functionName", getFunctionName());
        params.put("className", getClassName());
        params.put("packageName", getFunctionPackageName());

        prepareTemplateParameters(template, bindingTemplate, params);

        displayParameters(params);

        return params;
    }
753299
function loadTemplate(template, name, callback) {
  async.waterfall([
    cb => source(template.path, template.filter, template.readMode, cb),
    (files, cb) => asDataMap(files, template.mapping, cb),
  ], (error, result) => {
    async.nextTick(callback, error, result);
  });
}