@SuppressWarnings("resource")
  private void generate(TreeLogger logger, String template, TemplateGeneratorOptions options) {
    SourceBuilder<?> context = options.getContext(logger, template);
    InputStream input;
    try {
      if (new File(template).exists()) {
        input = new FileInputStream(template);
      } else {
        URL url = getClass().getClassLoader().getResource(template);
        if (url == null) {
          url = ClassLoader.getSystemResource(template);
          if (url == null) {
            logger.log(Type.ERROR, "You requested code generation for template " + template +
              ", but the file could not be found.");
            throw new CompilationFailed();
          }
        }
        input = url.openStream();
      }
      BufferedReader reader = new BufferedReader(new InputStreamReader(input));
      String line;
      while ((line = reader.readLine()) != null) {
        if (lineMatcher.matcher(line).matches()) {
          // we have a template command to parse!
          applyTemplate(logger, reader, context, options, line.trim());
        } else {
          context.getBuffer().append(line).append('\n');
        }
      }
      exportClass(logger, template, context, options);
    } catch (Exception e) {
      throw new CompilationFailed("Unable to generate java source file for template " + template, e);
    }
  }