Created
November 15, 2013 09:41
-
-
Save subchen/7481744 to your computer and use it in GitHub Desktop.
function assetsUrl(path) for jetbrick-template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FilenameFilter; | |
import java.util.HashMap; | |
import java.util.Map; | |
import javax.servlet.ServletContext; | |
import jetbrick.template.runtime.JetPageContext; | |
import jetbrick.template.web.JetWebContext; | |
public class AssetsUrlFunctions { | |
private static Map<String, String> mapping = new HashMap<String, String>(128); | |
public static String assetsUrl(JetPageContext ctx, String path) { | |
String url = mapping.get(path); | |
if (url != null) { | |
return url; | |
} | |
ServletContext sc = (ServletContext) ctx.getContext().get(JetWebContext.SERVLET_CONTEXT); | |
url = "/assets/" + path; | |
File file = new File(sc.getRealPath(url)); | |
if (!file.exists()) { | |
int pos = file.getName().lastIndexOf("."); | |
if (pos > 0) { | |
final String nameWithoutExt = file.getName().substring(0, pos); | |
final String ext = file.getName().substring(pos); | |
File[] files = file.getParentFile().listFiles(new FilenameFilter() { | |
@Override | |
public boolean accept(File dir, String name) { | |
return name.startsWith(nameWithoutExt + "-") && name.endsWith(ext); | |
} | |
}); | |
if (files != null && files.length > 0) { | |
url = url.replaceFirst("([^/\\\\]+)$", files[0].getName()); | |
} | |
} | |
} | |
url = sc.getContextPath() + url; | |
mapping.put(path, url); | |
return url; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment