All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hfg.javascript.JsUtil Maven / Gradle / Ivy

There is a newer version: 20240423
Show newest version
package com.hfg.javascript;

import com.hfg.util.io.StreamUtil;
import com.hfg.util.StringUtil;

import java.io.InputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


class JsUtil
{
   private static Pattern sUnsubstitutedTokenPattern = Pattern.compile("@@(\\S+)@@");

   //--------------------------------------------------------------------------
   protected static String getJSResourceAsString(String inResource)
   {

      return getJSResourceAsString(inResource, null);
   }

   //--------------------------------------------------------------------------
   protected static String getJSResourceAsString(String inResource, Map inTokenSubstitutionMap)
   {
      String js = null;
      try
      {
         js = StreamUtil.inputStreamToString(getJSResourceStream("resources/" + inResource));

         if (inTokenSubstitutionMap !=  null)
         {
            for (String token : inTokenSubstitutionMap.keySet())
            {
               // This could probably be done much more efficiently another way.
               js = js.replaceAll("@@" + token + "@@", inTokenSubstitutionMap.get(token));
            }
         }

         // Throw an exception if there are any unsubstituted tokens remaining.
         Matcher m = sUnsubstitutedTokenPattern.matcher(js);
         if (m.find())
         {
            throw new RuntimeException("Unsubstituted token " + StringUtil.singleQuote(m.group(1)) + " found in javascript!");
         }
      }
      catch (IOException e)
      {
         throw new RuntimeException("Problem retrieving javascript resource.", e);
      }

      return js;
   }

   //--------------------------------------------------------------------------
   protected static InputStream getJSResourceStream(String inResource)
   {
      InputStream stream = null;
      try
      {
         stream = JsUtil.class.getResourceAsStream(inResource);
         if (null == stream)
         {
            throw new RuntimeException("'" + inResource + "' couldn't be found!");
         }

         if (inResource.endsWith(".gz"))
         {
            stream = new GZIPInputStream(stream);
         }
      }
      catch (IOException e)
      {
         throw new RuntimeException("Problem retrieving javascript resource.", e);
      }

      return stream;
   }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy