@Override
  public void setResourceLoader(ResourceLoader resourceLoader) {
    if (Metadata.getCurrent().isWarDeployed()) {
      localResourceLoader = resourceLoader;
    } else {
      // The "settings" may be null in some of the Grails unit tests.
      BuildSettings settings = BuildSettingsHolder.getSettings();

      String location = null;
      if (settings != null) {
        location = settings.getResourcesDir().getPath();
      } else if (Environment.getCurrent().isReloadEnabled()) {
        location = Environment.getCurrent().getReloadLocation();
      }

      if (location != null) {
        localResourceLoader = new DevelopmentResourceLoader(application, location);
      } else {
        localResourceLoader = resourceLoader;
      }
    }
    super.setResourceLoader(localResourceLoader);

    if (resourceResolver == null) {
      resourceResolver = new PathMatchingResourcePatternResolver(localResourceLoader);
    }
  }
 private static List getBindingIncludeList(final Object object) {
   List includeList = Collections.emptyList();
   try {
     final Class<? extends Object> objectClass = object.getClass();
     if (CLASS_TO_BINDING_INCLUDE_LIST.containsKey(objectClass)) {
       includeList = CLASS_TO_BINDING_INCLUDE_LIST.get(objectClass);
     } else {
       final Field whiteListField =
           objectClass.getDeclaredField(DefaultASTDatabindingHelper.DEFAULT_DATABINDING_WHITELIST);
       if (whiteListField != null) {
         if ((whiteListField.getModifiers() & Modifier.STATIC) != 0) {
           final Object whiteListValue = whiteListField.get(objectClass);
           if (whiteListValue instanceof List) {
             includeList = (List) whiteListValue;
           }
         }
       }
       if (!Environment.getCurrent().isReloadEnabled()) {
         CLASS_TO_BINDING_INCLUDE_LIST.put(objectClass, includeList);
       }
     }
   } catch (Exception e) {
   }
   return includeList;
 }
  public GroovyPageParser(
      String name, String uri, String filename, String gspSource, String expressionCodecName)
      throws IOException {
    Config config = Holders.getConfig();
    if (config != null) {
      setEnableSitemeshPreprocessing(
          config.getProperty(
              GroovyPageParser.CONFIG_PROPERTY_GSP_SITEMESH_PREPROCESS,
              Boolean.class,
              enableSitemeshPreprocessing));
    }

    GrailsPluginInfo pluginInfo = null;
    //        TODO: figure out a way to restore plugin metadata for GSP
    //        if (filename != null && BuildSettingsHolder.getSettings() != null) {
    //            pluginInfo =
    // GrailsPluginUtils.getPluginBuildSettings().getPluginInfoForSource(filename);
    //            if (pluginInfo != null) {
    //                pluginAnnotation = "@GrailsPlugin(name='" + pluginInfo.getName() + "',
    // version='" +
    //                    pluginInfo.getVersion() + "')";
    //            }
    //        }

    OutputEncodingSettings gspConfig = new OutputEncodingSettings(config);

    this.expressionCodecDirectiveValue = expressionCodecName;
    if (expressionCodecDirectiveValue == null) {
      expressionCodecDirectiveValue =
          gspConfig.getCodecSettings(pluginInfo, OutputEncodingSettings.EXPRESSION_CODEC_NAME);
    }
    staticCodecDirectiveValue =
        gspConfig.getCodecSettings(pluginInfo, OutputEncodingSettings.STATIC_CODEC_NAME);
    outCodecDirectiveValue =
        gspConfig.getCodecSettings(pluginInfo, OutputEncodingSettings.OUT_CODEC_NAME);
    taglibCodecDirectiveValue =
        gspConfig.getCodecSettings(pluginInfo, OutputEncodingSettings.TAGLIB_CODEC_NAME);

    Map<String, String> directives = parseDirectives(gspSource);

    if (isSitemeshPreprocessingEnabled(directives.get(SITEMESH_PREPROCESS_DIRECTIVE))) {
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Preprocessing "
                + uri
                + " for sitemesh. Replacing head, title, meta and body elements with sitemesh:capture*.");
      }
      // GSP preprocessing for direct sitemesh integration: replace head -> g:captureHead, title ->
      // g:captureTitle, meta -> g:captureMeta, body -> g:captureBody
      gspSource = sitemeshPreprocessor.addGspSitemeshCapturing(gspSource);
      sitemeshPreprocessMode = true;
    }
    scan = new GroovyPageScanner(gspSource, uri);
    pageName = uri;
    environment = Environment.getCurrent();
    makeName(name);
    makeSourceName(filename);
  }
 private Resource getResourceWithinContext(String uri) {
   if (resourceLoader == null)
     throw new IllegalStateException(
         "TemplateEngine not initialised correctly, no [resourceLoader] specified!");
   if (Environment.getCurrent().isReloadEnabled() && Metadata.getCurrent().isWarDeployed()) {
     return resourceLoader.getResource(uri);
   }
   Resource r = servletContextLoader.getResource(uri);
   if (r.exists()) return r;
   return resourceLoader.getResource(uri);
 }
  private static ScriptAndArgs processAndReturnArguments(CommandLine commandLine) {
    ScriptAndArgs info = new ScriptAndArgs();
    if (Environment.isSystemSet()) {
      info.env = Environment.getCurrent().getName();
    } else if (commandLine.getEnvironment() != null) {
      info.env = commandLine.getEnvironment();
    }

    info.inputName = commandLine.getCommandName();
    info.name = GrailsNameUtils.getNameFromScript(commandLine.getCommandName());
    return info;
  }
  public void afterPropertiesSet() throws Exception {
    resourceLoader = GrailsResourceLoaderHolder.getResourceLoader();
    if (resourceLoader != null) {
      return;
    }

    if (Environment.getCurrent().isReloadEnabled()) {
      ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
      try {
        Resource[] resources =
            resolver.getResources(
                "file:" + Environment.getCurrent().getReloadLocation() + "/grails-app/**/*.groovy");
        resourceLoader = new GrailsResourceLoader(resources);
      } catch (IOException e) {
        createDefaultInternal();
      }
    } else {
      createDefaultInternal();
    }
    GrailsResourceLoaderHolder.setResourceLoader(resourceLoader);
  }
 /**
  * Get the default Compass connection (ie, Lucene index dir)
  *
  * @param grailsApplication the GrailsApplication - may be null
  * @return {user.home}/.grails/projects/{project-name}/searchable-index/{grails.env}
  */
 public static String getDefaultConnection(GrailsApplication grailsApplication) {
   String appName = SearchableUtils.getAppName(grailsApplication);
   return new StringBuilder(System.getProperty("user.home"))
       .append(File.separator)
       .append(".grails")
       .append(File.separator)
       .append("projects")
       .append(File.separator)
       .append(appName)
       .append(File.separator)
       .append("searchable-index")
       .append(File.separator)
       .append(Environment.getCurrent().getName())
       .toString();
 }
  /** Default constructor. */
  public ReloadAwareAutowireCapableBeanFactory() {
    reloadEnabled = GrailsUtil.isDevelopmentEnv() || Environment.getCurrent().isReloadEnabled();
    if (reloadEnabled) {

      // Implementation note: The default Spring InstantiationStrategy caches constructors.
      // This is no good at development time because if the class reloads then Spring
      // continues to use the old class. We deal with this here by disabling the caching
      // for development time only
      setInstantiationStrategy(
          new CglibSubclassingInstantiationStrategy() {
            @Override
            public Object instantiate(
                RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
              // Don't override the class with CGLIB if no overrides.
              if (beanDefinition.getMethodOverrides().isEmpty()) {
                Constructor<?> constructorToUse;
                Class<?> clazz = beanDefinition.getBeanClass();
                if (clazz.isInterface()) {
                  throw new BeanInstantiationException(clazz, "Specified class is an interface");
                }
                try {
                  constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
                } catch (Exception ex) {
                  throw new BeanInstantiationException(clazz, "No default constructor found", ex);
                }

                return BeanUtils.instantiateClass(constructorToUse);
              }
              // Must generate CGLIB subclass.
              return instantiateWithMethodInjection(beanDefinition, beanName, owner);
            }
          });
    }

    setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer());
    setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
    ignoreDependencyType(Closure.class);
  }
 public boolean supportsCurrentScopeAndEnvironment() {
   BuildScope bs = BuildScope.getCurrent();
   Environment e = Environment.getCurrent();
   return supportsEnvironment(e) && supportsScope(bs);
 }
  @SuppressWarnings("unchecked")
  private void evaluateOnChangeListener() {
    if (pluginBean.isReadableProperty(ON_SHUTDOWN)) {
      onShutdownListener =
          (Closure) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_SHUTDOWN);
    }
    if (pluginBean.isReadableProperty(ON_CONFIG_CHANGE)) {
      onConfigChangeListener =
          (Closure)
              GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_CONFIG_CHANGE);
    }
    if (pluginBean.isReadableProperty(ON_CHANGE)) {
      onChangeListener =
          (Closure) GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, ON_CHANGE);
    }

    final boolean warDeployed = Metadata.getCurrent().isWarDeployed();
    final boolean reloadEnabled = Environment.getCurrent().isReloadEnabled();

    if (!((reloadEnabled || !warDeployed) && onChangeListener != null)) {
      return;
    }

    Object referencedResources =
        GrailsClassUtils.getPropertyOrStaticPropertyOrFieldValue(plugin, WATCHED_RESOURCES);

    try {
      List resourceList = null;
      if (referencedResources instanceof String) {
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Configuring plugin "
                  + this
                  + " to watch resources with pattern: "
                  + referencedResources);
        }
        resourceList = new ArrayList();
        resourceList.add(referencedResources.toString());
      } else if (referencedResources instanceof List) {
        resourceList = (List) referencedResources;
      }

      if (resourceList != null) {
        List<String> resourceListTmp = new ArrayList<String>();
        PluginBuildSettings pluginBuildSettings = GrailsPluginUtils.getPluginBuildSettings();

        if (pluginBuildSettings != null) {

          final Resource[] pluginDirs = pluginBuildSettings.getPluginDirectories();
          final Environment env = Environment.getCurrent();
          final String baseLocation = env.getReloadLocation();

          for (Object ref : resourceList) {
            String stringRef = ref.toString();
            if (!warDeployed) {
              for (Resource pluginDir : pluginDirs) {
                if (pluginDir != null) {
                  String pluginResources =
                      getResourcePatternForBaseLocation(
                          pluginDir.getFile().getCanonicalPath(), stringRef);
                  resourceListTmp.add(pluginResources);
                }
              }
              addBaseLocationPattern(resourceListTmp, baseLocation, stringRef);
            } else {
              addBaseLocationPattern(resourceListTmp, baseLocation, stringRef);
            }
          }

          watchedResourcePatternReferences = new String[resourceListTmp.size()];
          for (int i = 0; i < watchedResourcePatternReferences.length; i++) {
            String resRef = resourceListTmp.get(i);
            watchedResourcePatternReferences[i] = resRef;
          }

          watchedResourcePatterns =
              new WatchPatternParser()
                  .getWatchPatterns(Arrays.asList(watchedResourcePatternReferences));
        }
      }
    } catch (IllegalArgumentException e) {
      if (GrailsUtil.isDevelopmentEnv()) {
        LOG.debug(
            "Cannot load plug-in resource watch list from ["
                + ArrayUtils.toString(watchedResourcePatternReferences)
                + "]. This means that the plugin "
                + this
                + ", will not be able to auto-reload changes effectively. Try runnng grails upgrade.: "
                + e.getMessage());
      }
    } catch (IOException e) {
      if (GrailsUtil.isDevelopmentEnv()) {
        LOG.debug(
            "Cannot load plug-in resource watch list from ["
                + ArrayUtils.toString(watchedResourcePatternReferences)
                + "]. This means that the plugin "
                + this
                + ", will not be able to auto-reload changes effectively. Try runnng grails upgrade.: "
                + e.getMessage());
      }
    }
  }
  @SuppressWarnings("rawtypes")
  @Override
  public GrailsClass getArtefactForFeature(Object featureId) {
    if (artefactInfo == null) {
      return null;
    }

    String uri;
    String pluginName = null;

    if (featureId instanceof Map) {
      Map featureIdMap = (Map) featureId;
      uri = (String) featureIdMap.get("uri");
      pluginName = (String) featureIdMap.get("pluginName");
    } else {
      uri = featureId.toString();
    }

    GrailsClass controllerClass = uriToControllerClassCache.get(uri);
    if (controllerClass == null) {
      final ApplicationContext mainContext = grailsApplication.getMainContext();
      GrailsPluginManager grailsPluginManager = null;
      if (mainContext.containsBean(GrailsPluginManager.BEAN_NAME)) {
        final Object pluginManagerBean = mainContext.getBean(GrailsPluginManager.BEAN_NAME);
        if (pluginManagerBean instanceof GrailsPluginManager) {
          grailsPluginManager = (GrailsPluginManager) pluginManagerBean;
        }
      }
      final GrailsClass[] controllerClasses = artefactInfo.getGrailsClasses();
      // iterate in reverse in order to pick up application classes first
      for (int i = (controllerClasses.length - 1); i >= 0; i--) {
        GrailsClass c = controllerClasses[i];
        if (((GrailsControllerClass) c).mapsToURI(uri)) {
          boolean foundController = false;
          if (pluginName != null && grailsPluginManager != null) {
            final GrailsPlugin pluginForClass = grailsPluginManager.getPluginForClass(c.getClazz());
            if (pluginForClass != null && pluginName.equals(pluginForClass.getName())) {
              foundController = true;
            }
          } else {
            foundController = true;
          }
          if (foundController) {
            controllerClass = c;
            break;
          }
        }
      }
      if (controllerClass == null) {
        controllerClass = NO_CONTROLLER;
      }

      // don't cache for dev environment
      if (Environment.getCurrent() != Environment.DEVELOPMENT) {
        uriToControllerClassCache.put(uri, controllerClass);
      }
    }

    if (controllerClass == NO_CONTROLLER) {
      controllerClass = null;
    }
    return controllerClass;
  }