01 import java.io.*; 
02 import java.util.*; 
03 import java.util.zip.*; 
04 import javax.servlet.*; 
05 import javax.servlet.http.*; 
06 
07 public class ViewFileCompress extends HttpServlet { 
08 
09  public void doGet(HttpServletRequest req, HttpServletResponse res) 
10                               throws ServletException, IOException { 
11 
12     OutputStream out = null; 
13 
14     /* Vyberieme vhodný typ kódovania založený na 
15     hodnote parametra Accept-Encoding. Vyberieme GZIP ak hlavička 
16     obsahuje "gzip". Alebo vyberieme ZIP ak hlavička 
17     obsahuje "compress". Posledná varianta je bez kompresie. */ 
18     
19     String encodings = req.getHeader("Accept-Encoding"); 
20     if (encodings != null && encodings.indexOf("gzip") != -1) { 
21      res.setHeader("Content-Encoding", "gzip"); 
22      out = new GZIPOutputStream(res.getOutputStream()); 
23     } 
24     else if (encodings != null && encodings.indexOf("compress") != -1) { 
25     res.setHeader("Content-Encoding", "x-compress");
26     out = new ZipOutputStream(res.getOutputStream()); 
27       ((ZipOutputStream)out).putNextEntry(new ZipEntry("zip_name")); 
28     } 
29     else { 
30      out = res.getOutputStream(); 
31     } 
32 
33     // získame odkaz na súbor 
34     String file = req.getPathTranslated(); 
35 
36     // ak nie je súbor, vrátime SC_FORBIDDEN 
37     if (file == null) { 
38      res.sendError(res.SC_FORBIDDEN); 
39      return; 
40     } 
41 
42     // získame a nastavíme typ súboru 
43     String contentType = getServletContext().getMimeType(file); 
44     res.setContentType(contentType); 
45 
46     // vrátime súbor využitím triedy interval.ServeFile 
47     try { 
48      ServeFile.returnFile(file, out); 
49     } 
50     catch (FileNotFoundException e) { 
51      res.sendError(res.SC_NOT_FOUND); 
52      return; 
53     } 
54     catch (IOException e) { 
55      getServletContext().log("Problém s posielaním súboru", e); 
56     } 
57   
58     out.close(); 
59   } 
60 }