import com.allaire.cfx.*;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.zip.*;
import java.io.*;

public class jzip implements CustomTag {
    public void processRequest(Request request, Response response) throws Exception {
        if(!request.attributeExists("zipfile"))
            throw new Exception("Missing zipfile parameter !!! You must pass a zipfile parameter, containing the fully qualified path and zip file name");
        if(!request.attributeExists("filelist"))
            throw new Exception("Missing filelist parameter !!! You must pass a filelist parameter, containing the fully qualified path and file name/s to be compressed");

        final int DATA_BLOCK_SIZE = 2048;
        int byteCount;
        
        FileOutputStream fos = new FileOutputStream(request.getAttribute("zipfile"));
        ZipOutputStream targetStream = new ZipOutputStream(fos);
        targetStream.setMethod(ZipOutputStream.DEFLATED);
        if (request.attributeExists("compression")) {
            targetStream.setLevel(Integer.parseInt(request.getAttribute("compression"))); 
        } else {
            targetStream.setLevel(Deflater.BEST_SPEED);
        }
        String s = request.getAttribute("filelist");
        StringTokenizer stringtokenizer = new StringTokenizer(s, ",");
        while(stringtokenizer.hasMoreTokens()){
            String dataFileName = stringtokenizer.nextToken();
	    try {	   
            FileInputStream fis = new FileInputStream(dataFileName);
            BufferedInputStream sourceStream = new BufferedInputStream(fis);
            ZipEntry theEntry = new ZipEntry(dataFileName);
            targetStream.putNextEntry(theEntry);
            byte[] data = new byte[DATA_BLOCK_SIZE];
            while ((byteCount = sourceStream.read(data, 0, DATA_BLOCK_SIZE)) != -1){
                targetStream.write(data, 0, byteCount);
            }
            targetStream.flush();
            targetStream.closeEntry();
            sourceStream.close();
            } catch (Exception e) {
		response.writeDebug("An error occurred while adding a file. The error message -: " + e.getMessage());
	    }
        }
        targetStream.close();
   }
}