Filter続き
- id:eccoHowling:20071025:p1
Responseに介入してTranscoderを噛ますのではなく、Requestを拾って事前にTranscoderを実行しておく形にしてみた。今回はNetBeansのテンプレートのままdoBeforeProcessingだけを実装した。FilterConfigにパスの正規表現やファイルタイプを設定しておく形にすればもっと汎用的になると思う。
以下コード。
private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) log("SVGRasterizeFilter:DoBeforeProcessing"); String path = ((HttpServletRequest) request).getServletPath(); Pattern pattern = Pattern.compile("^(.*)\\.jpg$"); Matcher matcher = pattern.matcher(path); if ( matcher.matches() ) { String svgPath = matcher.replaceAll("$1.svg"); ServletContext context = getFilterConfig().getServletContext(); File jpgFile = new File(context.getRealPath(path)); File svgFile = new File(context.getRealPath(svgPath)); if ( svgFile.exists() ) { if ( ! jpgFile.exists() || jpgFile.lastModified() < svgFile.lastModified() ) { try { Transcoder transcoder = new JPEGTranscoder(); TranscoderInput input = new TranscoderInput(new FileInputStream(svgFile)); TranscoderOutput output = new TranscoderOutput(new FileOutputStream(jpgFile)); transcoder.transcode(input, output); } catch (TranscoderException ex) { ex.printStackTrace(); } } } } }