001/*
002 * SonarQube
003 * Copyright (C) 2009-2017 SonarSource SA
004 * mailto:info AT sonarsource DOT com
005 *
006 * This program is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.api.web;
021
022import java.io.File;
023import java.io.FileNotFoundException;
024import java.io.IOException;
025import java.io.InputStream;
026import org.apache.commons.io.FileUtils;
027import org.apache.commons.io.IOUtils;
028import org.sonar.api.utils.SonarException;
029
030/**
031 * @since 1.11
032 * @deprecated since 6.3. This class is ignored.
033 */
034@Deprecated
035public abstract class AbstractRubyTemplate {
036
037  private String cache = null;
038
039  public String getTemplate() {
040    String result = loadTemplateFromCache();
041    try {
042      if (result == null) {
043        result = loadTemplateFromClasspath();
044      }
045      if (result == null) {
046        result = loadTemplateFromAbsolutePath();
047      }
048      return result;
049
050    } catch (IOException e) {
051      throw new SonarException("Can not read the file " + getTemplatePath(), e);
052    }
053  }
054
055  private String loadTemplateFromAbsolutePath() throws IOException {
056    File file = new File(getTemplatePath());
057    if (file.exists()) {
058      // the result is not cached
059      return FileUtils.readFileToString(file);
060    }
061    throw new FileNotFoundException(getTemplatePath());
062  }
063
064  private String loadTemplateFromClasspath() throws IOException {
065    InputStream input = getClass().getResourceAsStream(getTemplatePath());
066    try {
067      if (input != null) {
068        cache = IOUtils.toString(input);
069        return cache;
070      }
071    } finally {
072      IOUtils.closeQuietly(input);
073    }
074    return null;
075  }
076
077  protected String loadTemplateFromCache() {
078    return cache;
079  }
080
081  /**
082   * the path of the template. In production environment, it's the classloader path (for example "/org/sonar/my_template.erb").
083   * In dev mode, it's useful to return an absolute path (for example C:/temp/my_template.erb). In such a case the result is not cached.
084   */
085  protected abstract String getTemplatePath();
086
087}