1 17 package org.apache.geronimo.deployment.remote; 18 19 import javax.servlet.http.HttpServlet ; 20 import javax.servlet.http.HttpServletRequest ; 21 import javax.servlet.http.HttpServletResponse ; 22 import javax.servlet.ServletException ; 23 import java.io.DataOutputStream ; 24 import java.io.DataInputStream ; 25 import java.io.File ; 26 import java.io.IOException ; 27 import java.io.BufferedOutputStream ; 28 import java.io.FileOutputStream ; 29 30 51 public class FileUploadServlet extends HttpServlet { 52 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException { 53 int fileCount; 54 String names[]; 55 try { 56 DataInputStream in = new DataInputStream (request.getInputStream()); 57 fileCount = in.readInt(); 58 names = new String [fileCount]; 59 for(int i=0; i<fileCount; i++) { 60 int length = in.readInt(); 61 File temp = File.createTempFile("remote-deploy", ""); 62 temp.deleteOnExit(); 63 names[i] = temp.getAbsolutePath(); 64 readToFile(in, temp, length); 65 } 66 in.close(); 67 } catch (IOException e) { 68 DataOutputStream out = new DataOutputStream (response.getOutputStream()); 69 out.writeUTF("ERROR: "+e.getMessage()); 70 out.close(); 71 return; 72 } 73 DataOutputStream out = new DataOutputStream (response.getOutputStream()); 74 out.writeUTF("OK"); 75 out.writeInt(fileCount); 76 for (int i = 0; i < names.length; i++) { 77 out.writeUTF(names[i]); 78 } 79 out.flush(); 80 out.close(); 81 } 82 83 private static void readToFile(DataInputStream in, File temp, int length) throws IOException { 84 BufferedOutputStream out = new BufferedOutputStream (new FileOutputStream (temp)); 85 int total, read; 86 try { 87 byte[] buf = new byte[1024]; 88 total = 0; 89 while((read = in.read(buf, 0, Math.min(buf.length, length - total))) > -1) { 90 out.write(buf, 0, read); 91 total += read; 92 if(total == length) { 93 break; 94 } 95 } 96 } finally { 97 try {out.flush();} catch (IOException e) {} 98 out.close(); 99 } 100 if(total != length) { 101 throw new IOException ("Unable to read entire upload file ("+total+"b expecting "+length+"b)"); 102 } 103 } 104 } 105 106 | Popular Tags |