/*
 * Copyright 2010 Red Hat, Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.jboss.soa.dsp.example;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
 
public class DeployServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String TMP_DIR_PATH = "/tmp";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH ="/files";
	private File destinationDir;
 
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if(!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		if(!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
		}
 
	}
 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    PrintWriter out = response.getWriter();
	    response.setContentType("text/html");
	    out.println("<h1>Dynamic Service Provider Example</h1>");
	    out.println();
 
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
		/*
		 *Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above threshold.
		 */
		fileItemFactory.setRepository(tmpDir);
 
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if(item.isFormField()) {
					out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
				} else if (item.getName().endsWith(".zip") == false) {
					out.println("File must be a '.zip' archive!");
				} else {
					//Handle Uploaded files.
					out.println("Uploading File: "+item.getName()+"<br>");
					
					/*
					 * Write file to the ultimate location.
					 */
					File file = new File(destinationDir,item.getName().substring(0, item.getName().length()-4));
					
					file.mkdir();
					
					File wsdlFile=unzip(out, new java.util.zip.ZipInputStream(item.getInputStream()), file.getAbsolutePath());
					
					if (wsdlFile == null) {
						out.println("ERROR: No WSDL definition found!!!<br>");
					} else {
						// Invoke dynamic service deployment mechanism
						WSDeployer deployer=new WSDeployer();
						
						DeployStore.add(deployer.deploy(file, wsdlFile));
					}
					
					// Display undeployment options
					DSPExampleForm.buildForm(out);
				}
				
				out.close();
			}
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}
 
	}
	
	protected java.io.File unzip(PrintWriter out, ZipInputStream zis, String path) throws IOException {
		ZipEntry ze=null;
		java.io.File wsdlFile=null;
	    
	    out.println("Unzipping file ....<br>");

	    while ((ze=zis.getNextEntry()) != null) {
	    	
	    	if (ze.isDirectory()) {
	    		java.io.File f=new java.io.File(path+java.io.File.separatorChar+ze.getName());
	    		f.mkdirs();
	    	} else {
	    		out.println("Unzip: "+ze.getName()+"<br>");
	    		unzipEntry(zis, ze.getName(), path);
	    		
	    		if (ze.getName().endsWith(".wsdl")) {
	    			wsdlFile = new java.io.File(path+java.io.File.separatorChar+ze.getName());
	    		}
	    	}
	    }
	    
	    out.println("Zip unpacked.<br><br>");
	    zis.close();
	    
	    return(wsdlFile);
	}
	    
	protected void unzipEntry(ZipInputStream zis, String name, String path) throws IOException {
		System.out.println("\t\tunzipping "+name+"<br>");
		FileOutputStream fos = new FileOutputStream(path+java.io.File.separatorChar+name);
		byte[] b=new byte[1024];
		int len=0;
		
		while ((len=zis.read(b)) != -1) {
			fos.write(b,0,len);
		}
		
		fos.close();
	}
}