package ca.carleton.gcrc.javascript;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.SequenceInputStream;
import java.io.Writer;
import java.util.Vector;

/**
 * This class is used to create a minimized version of a library, based on a number
 * of Javascript input files.
 *
 */
public class CompressProcess {

	public void generate(LibraryConfiguration config, File outputFile) throws Exception {
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		try {
			fos = new FileOutputStream(outputFile);
			osw = new OutputStreamWriter(fos, "UTF-8");
			
			generate(config, osw);
			
			osw.flush();
			
		} catch(Exception e) {
			throw new Exception("Error while compressing javacript to file: "+outputFile,e);
			
		} finally {
			if( null != osw ){
				try {
					osw.close();
				} catch (Exception e) {
					// Ignore
				}
			}
			if( null != fos ){
				try {
					fos.close();
				} catch (Exception e) {
					// Ignore
				}
			}
		}
	}

	public void generate(LibraryConfiguration config, Writer writer) throws Exception {
		// Create input reader
		Reader reader = null;
		Vector<FileInputStream> streams = new Vector<FileInputStream>(); 
		SequenceInputStream sis = null;
		try {
			// Create sequence input stream from files in configuration
			for(File file : config.getInputFiles()){
				FileInputStream fis = new FileInputStream(file);
				streams.add(fis);
			}
			sis = new SequenceInputStream(streams.elements());
			reader = new InputStreamReader(sis, "UTF-8");
			
			JSMin jsMin = new JSMin(reader, writer);
			jsMin.jsmin();
			
		} catch(Exception e) {
			throw new Exception("Error while compressing javascript",e);
			
		} finally {
			if( null != reader ) {
				try {
					reader.close();
				} catch (Exception e) {
					// Ignore
				}
			}
			for(FileInputStream fis : streams){
				try {
					fis.close();
				} catch (Exception e) {
					// Ignore
				}
			}
			if( null != sis ) {
				try {
					sis.close();
				} catch (Exception e) {
					// Ignore
				}
			}
		}
	}
}

@@ -31,16 +31,53 @@
 cript;%0A%0A
+import java.io.ByteArrayInputStream;%0A
 import j
@@ -146,32 +146,60 @@
 leOutputStream;%0A
+import java.io.InputStream;%0A
 import java.io.I
@@ -1301,28 +1301,24 @@
 l;%0A%09%09Vector%3C
-File
 InputStream%3E
@@ -1339,20 +1339,16 @@
  Vector%3C
-File
 InputStr
@@ -1398,16 +1398,88 @@
 %09%09try %7B%0A
+%09%09%09// Create end of line byte array%0A%09%09%09byte%5B%5D eol = %7B (byte)'%5Cn' %7D;%0A%09%09%09%0A
 %09%09%09// Cr
@@ -1652,16 +1652,107 @@
 d(fis);%0A
+%09%09%09%09%0A%09%09%09%09ByteArrayInputStream bais = new ByteArrayInputStream(eol);%0A%09%09%09%09streams.add(bais);%0A
 %09%09%09%7D%0A%09%09%09
@@ -2146,20 +2146,16 @@
 %0A%09%09%09for(
-File
 InputStr

Insert eol at the end of each javascript file before minimizing. Issue #13