Finds the templates that can apply to a given application.
@param appName an application name (can be null to match all)
@param templates a non-null collection of templates
@return a non-null collection of templates
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;
	}
588366
public ThymeLeafTemplateImplementation getTemplateByResourceName(String resourceName) {
        Collection<ThymeLeafTemplateImplementation> list = registrations.keySet();
        for (ThymeLeafTemplateImplementation template : list) {
            if (template.fullName().endsWith(resourceName)
                    || template.fullName().endsWith(resourceName + "." + extension())) {
                return template;
            }
            if (template.name().equals(resourceName)) {
                return template;
            }
        }
        return null;
    }
222538
def get_template_sources(self, template_name):
        
        if ':' not in template_name:
            self.reset(True)
            return

        app, template_path = template_name.split(':')
        if app:
            yield NamespaceOrigin(
                app_name=app,
                name='app_namespace:%s:%s' % (app, template_name),
                template_name=template_path,
                loader=self)
            return

        self.reset(False)
        for app in self.app_templates_dirs:
            file_path = self.get_app_template_path(app, template_path)
            if file_path in self._already_used:
                continue
            self._already_used.append(file_path)
            yield NamespaceOrigin(
                app_name=app,
                name='app_namespace:%s:%s' % (app, template_name),
                template_name=template_path,
                loader=self)
1235107
public static PredicateTemplate predicateTemplate(String template, Object... args) {
        return predicateTemplate(TemplateFactory.DEFAULT.create(template), ImmutableList.copyOf(args));
    }
1207267
static String[] computeTemplates(String[] templates, String classpathRoot) {
        if (templates == null || templates.length == 0) {
            if (logger.isDebugEnabled()) {
                logger.debug("Automatic discovery is activated. Looking for template files in classpath under [{}].",
                        classpathRoot);
            }

            ArrayList<String> autoTemplates = new ArrayList<>();

            try {
                // Let's scan our resources
                List<String> scannedTemplates = TemplateFinder.findTemplates(classpathRoot);
                for (String template : scannedTemplates) {
                    autoTemplates.add(template);
                }

                return autoTemplates.toArray(new String[autoTemplates.size()]);
            } catch (IOException|URISyntaxException e) {
                logger.debug("Automatic discovery does not succeed for finding json files in classpath under " + classpathRoot + ".");
                logger.trace("", e);
            }
        }
        return templates;
    }
70183
public static String[] getTemplatesCalled(String basePath, String templateName) {

        final HashMap<String, String> templatesCalledMap =
            new HashMap<String, String>();

        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");
            }


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

            // Search for embedded execute methods.
            CodeDisassembler cd = new CodeDisassembler(executeMethod);
            cd.disassemble(new CodeAssemblerPrinter(executeMethod
                .getMethodDescriptor().getParameterTypes(), true, null) {

                 public void invokeStatic(String className, String methodName,
                     TypeDesc ret, TypeDesc[] params)  {
                     if (JavaClassGenerator.EXECUTE_METHOD_NAME.equals(methodName))
                         templatesCalledMap.put(className.replace('.', '/'), className);
                 }

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

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

            if (substituteMethod == null)
                return (String[]) templatesCalledMap.keySet().toArray(
                    new String[templatesCalledMap.keySet().size()]);

            // Search for embedded substitute methods.
            cd = new CodeDisassembler(substituteMethod);
            cd.disassemble(new CodeAssemblerPrinter(substituteMethod
                .getMethodDescriptor().getParameterTypes(), true, null) {

                 public void invokeStatic(String className, String methodName,
                     TypeDesc ret, TypeDesc[] params)  {
                     if (JavaClassGenerator.EXECUTE_METHOD_NAME.equals(methodName))
                         templatesCalledMap.put(className.replace('.', '/'), className);
                 }

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

        return (String[]) templatesCalledMap.keySet().toArray(
            new String[templatesCalledMap.keySet().size()]);
    }
677987
def render_template(request, app, template_name, context=None, subdir="templates", def_name=None):
    '''
    
    '''
    return get_template(app, template_name, subdir).render(context, request, def_name)
411511
public static <T> TemplateExpression<T> template(Class<? extends T> cl, String template, Object... args) {
        return template(cl, TemplateFactory.DEFAULT.create(template), ImmutableList.copyOf(args));
    }
1186016
public static ClassLoader getAppClassLoader(String appName) {
        ClassLoader appClassLoader = APPNAME_CLASSLOADER_MAP.get(appName);
        if (appClassLoader == null) {
            return ClassLoaderUtils.getCurrentClassLoader();
        } else {
            return appClassLoader;
        }
    }
565767
public TemplateFilter names(String... names) {
        allItemsNotNull(names, "Template names");

        predicate = predicate.and(combine(
            TemplateMetadata::getName, in(names)
        ));

        return this;
    }
1063770
def get_template(template_name,fields=None):
    '''
    '''
    template = None
    if not template_name.endswith('.html'):
        template_name = "%s.html" %(template_name)
    here = "%s/cli/app/templates" %(get_installdir())
    template_path = "%s/%s" %(here,template_name)
    if os.path.exists(template_path):
        template = ''.join(read_file(template_path))
    if fields is not None:
        for tag,sub in fields.items():
            template = template.replace(tag,sub)
    return template
733510
private final CompiledST loadTemplateResource(String prefix, String unqualifiedFileName) {
        //if (resourceRoot == null) return null;
        //return loadTemplate(resourceRoot, prefix, unqualifiedFileName);
        if (resourceRoots.isEmpty()) return null;
        CompiledST template = null;
        for (URL resourceRoot : resourceRoots) {
            if ((template = loadTemplate(resourceRoot, prefix, unqualifiedFileName)) != null)
                return template;
        }
        return null;
    }
1194363
void generate( Application application, Collection<TemplateEntry> templates ) {

		try {
			synchronized( this.generationLock ) {
				TemplateUtils.generate( application, this.outputDIR, templates, this.logger );
			}

		} catch( IOException e ) {
			this.logger.warning( "An error occurred while generating files from templates for application " + application );
			Utils.logException( this.logger, e );

		} catch( Throwable e ) {
			this.logger.warning( "An unexpected error occurred while generating files from templates for application " + application );
			Utils.logException( this.logger, new UndeclaredThrowableException( e ));
		}
	}
1209873
public OvhTemplates templateName_GET(String templateName) throws IOException {
		String qPath = "/dedicated/installationTemplate/{templateName}";
		StringBuilder sb = path(qPath, templateName);
		String resp = execN(qPath, "GET", sb.toString(), null);
		return convertTo(resp, OvhTemplates.class);
	}
440235
void generate( Application application ) {

		// Get the templates
		Collection<TemplateEntry> templates = Collections.emptyList();
		synchronized( this.watcherLock ) {
			if( this.templateWatcher != null )
				templates = this.templateWatcher.findTemplatesForApplication( application.getName());
		}

		// Process them
		generate( application, templates );
	}
906277
@Override
	public List<TargetAssociation> findTargetAssociations( String applicationName ) {

		this.logger.fine( "Request: find target associations in " + applicationName + "." );
		List<TargetAssociation> result = new ArrayList<> ();

		Application app = this.manager.applicationMngr().findApplicationByName( applicationName );
		if( app != null ) {

			// Default target for the application.
			// It must be in first position.
			String defaultTargetId = this.manager.targetsMngr().findTargetId( app, null );
			TargetWrapperDescriptor twd = null;
			if( defaultTargetId != null )
				twd = this.manager.targetsMngr().findTargetById( defaultTargetId );

			result.add( new TargetAssociation( "", null, twd ));

			// Then, show the scoped instances.
			// List them, even if they do not have an associated target.
			for( Instance inst : InstanceHelpers.findAllScopedInstances( app )) {
				String instancePath = InstanceHelpers.computeInstancePath( inst );
				String targetId = this.manager.targetsMngr().findTargetId( app, instancePath, true );

				twd = null;
				if( targetId != null )
					twd = this.manager.targetsMngr().findTargetById( targetId );

				result.add( new TargetAssociation( instancePath, inst.getComponent().getName(), twd ));
			}

			// Deal with components.
			for( Component comp : ComponentHelpers.findAllComponents( app )) {
				if( ! ComponentHelpers.isTarget( comp ))
					continue;

				String key = "@" + comp.getName();
				String targetId = this.manager.targetsMngr().findTargetId( app, key, true );

				twd = null;
				if( targetId != null )
					twd = this.manager.targetsMngr().findTargetById( targetId );

				result.add( new TargetAssociation( key, null, twd ));
			}
		}

		return result;
	}
719206
@Override
	public Response getApplicationBindings( String applicationName ) {

		Response response;
		ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName );
		if( ma == null ) {
			response = handleError(
					Status.NOT_FOUND,
					new RestError( REST_INEXISTING, application( applicationName )),
					lang( this.manager )).build();

		} else {
			ApplicationBindings bindings = new ApplicationBindings();

			// Find all the external prefixes to resolve
			for( Component c : ComponentHelpers.findAllComponents( ma.getApplication())) {
				for( ImportedVariable var : ComponentHelpers.findAllImportedVariables( c ).values()) {
					if( ! var.isExternal())
						continue;

					String prefix = VariableHelpers.parseVariableName( var.getName()).getKey();
					bindings.prefixToItems.put( prefix, new ArrayList<ApplicationBindingItem> ());
				}
			}

			// Find all the applications that match a given prefix
			for( ManagedApplication managedApp : this.manager.applicationMngr().getManagedApplications()) {

				// Any potential bindings with this application?
				// There should be AT MOST 1 matching template for a given prefix.
				// One template means there can be several applications.
				String prefix = managedApp.getApplication().getTemplate().getExternalExportsPrefix();
				if( prefix == null || ! bindings.prefixToItems.containsKey( prefix ))
					continue;

				// There is a potential match. Is there an effective bound?
				Set<String> boundApps = ma.getApplication().getApplicationBindings().get( prefix );
				boolean bound = boundApps != null && boundApps.contains( managedApp.getName());
				ApplicationBindingItem item = new ApplicationBindingItem( managedApp.getName(), bound );
				bindings.prefixToItems.get( prefix ).add( item );
			}

			response = Response.ok().entity( bindings ).build();
		}

		return response;
	}