Advertisement
Guest User

HtmCache

a guest
May 1st, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.62 KB | None | 0 0
  1. /*
  2.  * This program is free software: you can redistribute it and/or modify it under the terms of the
  3.  * GNU General Public License as published by the Free Software Foundation, either version 3 of the
  4.  * License, or (at your option) any later version.
  5.  *
  6.  * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
  7.  * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  8.  * General Public License for more details.
  9.  *
  10.  * You should have received a copy of the GNU General Public License along with this program. If
  11.  * not, see <http://www.gnu.org/licenses/>.
  12.  */
  13. package com.l2dc.gameserver.cache;
  14.  
  15. import java.io.BufferedInputStream;
  16. import java.io.File;
  17. import java.io.FileFilter;
  18. import java.io.FileInputStream;
  19. import java.util.Arrays;
  20. import java.util.HashSet;
  21. import java.util.concurrent.ConcurrentHashMap;
  22.  
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25.  
  26. import com.l2dc.Config;
  27. import com.l2dcproject.commons.util.ResourceUtil;
  28. import com.l2dc.gameserver.model.actor.instance.L2PcInstance;
  29. import com.l2dc.gameserver.templates.htm.HtmTemplateEngine;
  30. import com.l2dc.gameserver.util.Util;
  31.  
  32. /**
  33.  * @author Layane
  34.  *
  35.  */
  36. public class HtmCache
  37. {
  38.     private static final Logger LOG = LoggerFactory.getLogger(HtmCache.class);
  39.  
  40.     private final ConcurrentHashMap<String, String> _cache = new ConcurrentHashMap<String, String>();
  41.  
  42.     private static final String[] VALID_TAGS = { "column", "unknown", "ul", "u",
  43.         "tt", "tr", "title", "textcode", "textarea", "td", "table", "sup", "sub",
  44.         "strike", "spin", "select", "right", "pre", "p", "option", "ol", "multiedit",
  45.         "li", "left", "input", "img", "i", "html", "h7", "h6", "h5", "h4", "h3", "h2",
  46.         "h1", "font", "extend", "edit", "comment", "combobox", "center", "button", "br",
  47.         "br1", "body", "bar", "address", "a", "sel", "list", "var", "fore", "readonl",
  48.         "rows", "valign", "fixwidth", "bordercolorli", "bordercolorda", "bordercolor",
  49.         "border", "bgcolor", "background", "align", "valu", "readonly", "multiple",
  50.         "selected", "typ", "type", "maxlength", "checked", "src", "y", "x", "querydelay",
  51.         "noscrollbar", "imgsrc", "b", "fg", "size", "face", "color", "deffon", "deffixedfont",
  52.         "width", "value", "tooltip", "name", "min", "max", "height", "disabled", "align",
  53.         "msg", "link", "href", "action", "head", "tbody", "!--" };
  54.  
  55.     private final static HashSet<String> VALID_TAGS_SET = new HashSet<String>(301);
  56.  
  57.     static
  58.     {
  59.         VALID_TAGS_SET.addAll(Arrays.asList(VALID_TAGS));
  60.     }
  61.  
  62.     private int _loadedFiles;
  63.     private long _bytesBuffLen;
  64.  
  65.     /**
  66.      *
  67.      * @return
  68.      */
  69.     public static HtmCache getInstance()
  70.     {
  71.         return SingletonHolder.INSTANCE;
  72.     }
  73.  
  74.     private HtmCache()
  75.     {
  76.         init(Config.DATAPACK_ROOT);
  77.     }
  78.  
  79.     /**
  80.      *
  81.      */
  82.     public void reload()
  83.     {
  84.         HtmTemplateEngine.getInstance().reload();
  85.         init(Config.DATAPACK_ROOT);
  86.     }
  87.  
  88.     /**
  89.      *
  90.      * @param f
  91.      */
  92.     public void init(File f)
  93.     {
  94.         if (!Config.LAZY_CACHE)
  95.         {
  96.             LOG.info("Html cache start...");
  97.             parseDir(f);
  98.             LOG.info("Cache[HTML]: {} megabytes on {} files loaded", String.format("%.3f", getMemoryUsage()), getLoadedFiles());
  99.         }
  100.         else
  101.         {
  102.             _cache.clear();
  103.             _loadedFiles = 0;
  104.             _bytesBuffLen = 0;
  105.             LOG.info("Cache[HTML]: Running lazy cache");
  106.         }
  107.     }
  108.  
  109.     /**
  110.      *
  111.      * @param f
  112.      */
  113.     public void reloadPath(File f)
  114.     {
  115.         parseDir(f);
  116.         LOG.info("Cache[HTML]: Reloaded specified path");
  117.     }
  118.  
  119.     /**
  120.      *
  121.      * @return
  122.      */
  123.     public double getMemoryUsage()
  124.     {
  125.         return ((float) _bytesBuffLen / 1048576);
  126.     }
  127.  
  128.     /**
  129.      *
  130.      * @return
  131.      */
  132.     public int getLoadedFiles()
  133.     {
  134.         return _loadedFiles;
  135.     }
  136.  
  137.     private static class HtmFilter implements FileFilter
  138.     {
  139.         public HtmFilter()
  140.         {
  141.         }
  142.  
  143.         @Override
  144.         public boolean accept(File file)
  145.         {
  146.             if (!file.isDirectory())
  147.             {
  148.                 return (file.getName().endsWith(".htm") || file.getName().endsWith(".html"));
  149.             }
  150.             return true;
  151.         }
  152.     }
  153.  
  154.     private void parseDir(File dir)
  155.     {
  156.         final FileFilter filter = new HtmFilter();
  157.         final File[] files = dir.listFiles(filter);
  158.  
  159.         for (File file : files)
  160.         {
  161.             if (!file.isDirectory())
  162.                 loadFile(file);
  163.             else
  164.                 parseDir(file);
  165.         }
  166.     }
  167.  
  168.     /**
  169.      *
  170.      * @param file
  171.      * @return
  172.      */
  173.     public String loadFile(File file)
  174.     {
  175.         final String relpath = Util.getRelativePath(Config.DATAPACK_ROOT, file);
  176.  
  177.         final HtmFilter filter = new HtmFilter();
  178.  
  179.         if (file.exists() && filter.accept(file) && !file.isDirectory())
  180.         {
  181.             String content;
  182.             FileInputStream fis = null;
  183.  
  184.             try
  185.             {
  186.                 fis = new FileInputStream(file);
  187.                 BufferedInputStream bis = new BufferedInputStream(fis);
  188.                 final int bytes = bis.available();
  189.                 final byte[] raw = new byte[bytes];
  190.  
  191.                 bis.read(raw);
  192.                 bis.close();
  193.                 content = new String(raw, "UTF-8");
  194.                 content = content.replaceAll("\r\n", "\n");
  195.                 content = HtmTemplateEngine.getInstance().prepare(content, file.getAbsolutePath());
  196.  
  197.                 String oldContent = _cache.get(relpath);
  198.  
  199.                 if (oldContent == null)
  200.                 {
  201.                     _bytesBuffLen += bytes;
  202.                     _loadedFiles++;
  203.                 }
  204.                 else
  205.                 {
  206.                     _bytesBuffLen = _bytesBuffLen - oldContent.length() + bytes;
  207.                 }
  208.  
  209.                 if(!Config.LAZY_CACHE)
  210.                     validate(file.getPath(), content);
  211.  
  212.                 _cache.put(relpath, content);
  213.  
  214.                 return content;
  215.             }
  216.             catch (Exception e)
  217.             {
  218.                 LOG.error("Cache[HTML]: Problem with htm file {}", file.getAbsolutePath(), e);
  219.             }
  220.             finally
  221.             {
  222.                 ResourceUtil.closeInputStream(fis);
  223.             }
  224.         }
  225.  
  226.         return null;
  227.     }
  228.  
  229.     /**
  230.      *
  231.      * @param path
  232.      * @param player
  233.      * @return
  234.      */
  235.     public String getHtmForce(String path, L2PcInstance player)
  236.     {
  237.         String content = getHtm(path, player);
  238.  
  239.         if (content == null)
  240.         {
  241.             content = "<html><body>My text is missing:<br>" + path + "</body></html>";
  242.             LOG.warn("Cache[HTML]: Missing HTML page: {}", path);
  243.         }
  244.  
  245.         return content;
  246.     }
  247.  
  248.     /**
  249.      *
  250.      * @param path
  251.      * @param player
  252.      * @return
  253.      */
  254.     public String getHtm(String path, L2PcInstance player)
  255.     {
  256.         return getHtm(path, player, null);
  257.     }
  258.    
  259.     /**
  260.      *
  261.      * @param path
  262.      * @param player
  263.      * @param htmlPrefix - Temp parameter for community board caching, should be removed asap
  264.      * @return
  265.      */
  266.     public String getHtm(String path, L2PcInstance player, String htmlPrefix)
  267.     {
  268.         String newPath = null;
  269.         String content;
  270.         if (player != null)
  271.         {
  272.             newPath = player.getHtmlPrefix() + path;
  273.             content = getHtm(newPath);
  274.             if (content != null)
  275.                 return HtmTemplateEngine.getInstance().parse(content, player, path);
  276.         } else if(htmlPrefix != null && !htmlPrefix.isEmpty()) {
  277.             newPath = htmlPrefix + path;
  278.             content = getHtm(newPath);
  279.             if (content != null)
  280.                 return content;
  281.         }
  282.  
  283.         content = getHtm(path);
  284.         if (content != null && newPath != null)
  285.             _cache.put(newPath, content);
  286.  
  287.         return HtmTemplateEngine.getInstance().parse(content, player, path);
  288.     }
  289.  
  290.     private String getHtm(String path)
  291.     {
  292.         if (path == null || path.isEmpty())
  293.             return ""; // avoid possible NPE
  294.  
  295.         String content = _cache.get(path);
  296.  
  297.         if (Config.LAZY_CACHE && content == null)
  298.             content = loadFile(new File(Config.DATAPACK_ROOT, path));
  299.  
  300.         return content;
  301.     }
  302.  
  303.     /**
  304.      *
  305.      * @param path
  306.      * @return
  307.      */
  308.     public boolean contains(String path)
  309.     {
  310.         return _cache.containsKey(path);
  311.     }
  312.  
  313.     /**
  314.      * Check if an HTM exists and can be loaded
  315.      *
  316.      * @param path
  317.      *            The path to the HTM
  318.      * @return  
  319.      * */
  320.     public boolean isLoadable(String path)
  321.     {
  322.         File file = new File(Config.DATAPACK_ROOT, path);
  323.         HtmFilter filter = new HtmFilter();
  324.  
  325.         if (file.exists() && filter.accept(file) && !file.isDirectory())
  326.             return true;
  327.  
  328.         return false;
  329.     }
  330.  
  331.     private void validate(String filename, String html)
  332.     {
  333.         outer: for (int begin = 0; (begin = html.indexOf('<', begin)) != -1; begin++)
  334.         {
  335.             int end;
  336.             for (end = begin; end < html.length(); end++)
  337.             {
  338.                 if (html.charAt(end) == '>' || html.charAt(end) == ' ')
  339.                     break;
  340.                 // some special quest-replaced tag
  341.                 if (end == begin + 1 && html.charAt(end) == '?')
  342.                     continue outer;
  343.             }
  344.             end++;
  345.             String tag = html.substring(begin + 1, end - 1).toLowerCase().replaceAll("/", "");
  346.             if (!VALID_TAGS_SET.contains(tag))
  347.             {
  348.                 LOG.info("Cache[HTML]: Invalid tag used: '{}' at pos {} {}", new Object[] {tag, (begin + 1), filename});
  349.             }
  350.         }
  351.     }
  352.  
  353.  
  354.     @SuppressWarnings("synthetic-access")
  355.     private static class SingletonHolder
  356.     {
  357.         protected static final HtmCache INSTANCE = new HtmCache();
  358.     }
  359. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement