001/* 002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Jean-Marc Orliaguet, Chalmers 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.theme.html; 023 024import java.io.ByteArrayInputStream; 025import java.io.ByteArrayOutputStream; 026import java.io.IOException; 027import java.io.InputStream; 028import java.io.OutputStream; 029 030import org.apache.commons.logging.Log; 031import org.apache.commons.logging.LogFactory; 032import org.nuxeo.theme.html.JSMin.UnterminatedCommentException; 033import org.nuxeo.theme.html.JSMin.UnterminatedRegExpLiteralException; 034import org.nuxeo.theme.html.JSMin.UnterminatedStringLiteralException; 035import org.nuxeo.theme.themes.ThemeException; 036 037public final class JSUtils { 038 039 static final Log log = LogFactory.getLog(JSUtils.class); 040 041 public static String compressSource(final String source) throws ThemeException { 042 String compressedSource = source; 043 InputStream in = null; 044 OutputStream out = null; 045 046 try { 047 in = new ByteArrayInputStream(source.getBytes()); 048 out = new ByteArrayOutputStream(); 049 050 JSMin compressor = new JSMin(in, out); 051 try { 052 compressor.jsmin(); 053 } catch (UnterminatedRegExpLiteralException e) { 054 throw new ThemeException("Could not compress javascript", e); 055 } catch (UnterminatedCommentException e) { 056 throw new ThemeException("Could not compress javascript", e); 057 } catch (UnterminatedStringLiteralException e) { 058 throw new ThemeException("Could not compress javascript", e); 059 } 060 compressedSource = out.toString(); 061 } catch (IOException e) { 062 throw new ThemeException("Could not compress javascript", e); 063 } finally { 064 if (out != null) { 065 try { 066 out.close(); 067 } catch (IOException e) { 068 log.error(e, e); 069 } finally { 070 out = null; 071 } 072 } 073 } 074 if (in != null) { 075 try { 076 in.close(); 077 } catch (IOException e) { 078 log.error(e, e); 079 } finally { 080 in = null; 081 } 082 } 083 084 return compressedSource; 085 } 086 087}