com.hfg.javascript.JsUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of com_hfg Show documentation
Show all versions of com_hfg Show documentation
com.hfg xml, html, svg, and bioinformatics utility library
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;
}
}