001/* 002 * (C) Copyright 2006-2007 Nuxeo SAS <http://nuxeo.com> and others 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * Jean-Marc Orliaguet, Chalmers 011 * 012 * $Id$ 013 */ 014 015package org.nuxeo.theme.html; 016 017import java.io.ByteArrayInputStream; 018import java.io.ByteArrayOutputStream; 019import java.io.IOException; 020import java.io.InputStream; 021import java.io.OutputStream; 022 023import org.apache.commons.logging.Log; 024import org.apache.commons.logging.LogFactory; 025import org.nuxeo.theme.html.JSMin.UnterminatedCommentException; 026import org.nuxeo.theme.html.JSMin.UnterminatedRegExpLiteralException; 027import org.nuxeo.theme.html.JSMin.UnterminatedStringLiteralException; 028import org.nuxeo.theme.themes.ThemeException; 029 030public final class JSUtils { 031 032 static final Log log = LogFactory.getLog(JSUtils.class); 033 034 public static String compressSource(final String source) throws ThemeException { 035 String compressedSource = source; 036 InputStream in = null; 037 OutputStream out = null; 038 039 try { 040 in = new ByteArrayInputStream(source.getBytes()); 041 out = new ByteArrayOutputStream(); 042 043 JSMin compressor = new JSMin(in, out); 044 try { 045 compressor.jsmin(); 046 } catch (UnterminatedRegExpLiteralException e) { 047 throw new ThemeException("Could not compress javascript", e); 048 } catch (UnterminatedCommentException e) { 049 throw new ThemeException("Could not compress javascript", e); 050 } catch (UnterminatedStringLiteralException e) { 051 throw new ThemeException("Could not compress javascript", e); 052 } 053 compressedSource = out.toString(); 054 } catch (IOException e) { 055 throw new ThemeException("Could not compress javascript", e); 056 } finally { 057 if (out != null) { 058 try { 059 out.close(); 060 } catch (IOException e) { 061 log.error(e, e); 062 } finally { 063 out = null; 064 } 065 } 066 } 067 if (in != null) { 068 try { 069 in.close(); 070 } catch (IOException e) { 071 log.error(e, e); 072 } finally { 073 in = null; 074 } 075 } 076 077 return compressedSource; 078 } 079 080}