KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > compiere > wstore > AssetServlet


1 /******************************************************************************
2  * The contents of this file are subject to the Compiere License Version 1.1
3  * ("License"); You may not use this file except in compliance with the License
4  * You may obtain a copy of the License at http://www.compiere.org/license.html
5  * Software distributed under the License is distributed on an "AS IS" basis,
6  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
7  * the specific language governing rights and limitations under the License.
8  * The Original Code is Compiere ERP & CRM Smart Business Solution
9  * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc.
10  * Portions created by Jorg Janke are Copyright (C) 1999-2003 Jorg Janke, parts
11  * created by ComPiere are Copyright (C) ComPiere, Inc.; All Rights Reserved.
12  * Contributor(s): ______________________________________.
13  *****************************************************************************/

14 package org.compiere.wstore;
15
16 import javax.servlet.*;
17 import javax.servlet.http.*;
18 import java.io.*;
19 import java.util.*;
20 import java.sql.*;
21 import java.util.zip.*;
22
23 import org.apache.ecs.*;
24 import org.apache.ecs.xhtml.*;
25
26 import org.compiere.util.*;
27 import org.compiere.www.*;
28 import org.compiere.model.*;
29
30 /**
31  * Assets.
32  *
33  * @author Jorg Janke
34  * @version $Id: AssetServlet.java,v 1.9 2003/10/04 03:58:26 jjanke Exp $
35  */

36 public class AssetServlet extends HttpServlet
37 {
38     /** Logging */
39     private Logger log = Logger.getCLogger(getClass());
40     /** Name */
41     static public final String JavaDoc NAME = "loginServlet";
42     /** Attribute */
43     static public final String JavaDoc ATTR_CHECKOUT = "CheckOut";
44
45     /**
46      * Initialize global variables
47      *
48      * @param config Configuration
49      * @throws ServletException
50      */

51     public void init(ServletConfig config)
52         throws ServletException
53     {
54         super.init(config);
55         if (!WEnv.initWeb(config))
56             throw new ServletException("AssetServlet.init");
57     } // init
58

59     /**
60      * Get Servlet information
61      * @return Info
62      */

63     public String JavaDoc getServletInfo()
64     {
65         return "Compiere Web Assets Servlet";
66     } // getServletInfo
67

68     /**
69      * Clean up resources
70      */

71     public void destroy()
72     {
73         log.debug("destroy");
74     } // destroy
75

76
77     /**
78      * Process the HTTP Get request.
79      * (logout, deleteCookie)
80      * Sends Web Request Page
81      *
82      * @param request request
83      * @param response response
84      * @throws ServletException
85      * @throws IOException
86      */

87     public void doGet(HttpServletRequest request, HttpServletResponse response)
88         throws ServletException, IOException
89     {
90         log.info("doGet from " + request.getRemoteHost() + " - " + request.getRemoteAddr());
91
92         String JavaDoc url = "assets.jsp";
93         //
94
HttpSession session = request.getSession(false);
95         if (session == null || session.getAttribute(Info.NAME) == null)
96             url = "login.jsp";
97         else
98         {
99             session.removeAttribute(JSPEnv.HDR_MESSAGE);
100             Info info = (Info)session.getAttribute(Info.NAME);
101             if (info != null)
102                 info.setMessage("");
103
104             // Parameter = Asset_ID - if invoice is valid and belongs to wu then create PDF & stream it
105
String JavaDoc msg = streamAsset(request, response);
106             if (msg == null || msg.length() == 0)
107                 return;
108             if (info != null)
109                 info.setMessage(msg);
110         }
111
112         log.info ("doGet - Forward to " + url);
113         RequestDispatcher dispatcher = getServletContext ().getRequestDispatcher (url);
114         dispatcher.forward (request, response);
115     } // doGet
116

117     /**
118      * Process the HTTP Post request
119      *
120      * @param request request
121      * @param response response
122      * @throws ServletException
123      * @throws IOException
124      */

125     public void doPost(HttpServletRequest request, HttpServletResponse response)
126         throws ServletException, IOException
127     {
128         doGet(request,response);
129     } // doPost
130

131     /**
132      * Stream asset
133      * @param request request
134      * @param response response
135      * @return "" or error message
136      */

137     private String JavaDoc streamAsset (HttpServletRequest request, HttpServletResponse response)
138     {
139         // Get Asset ID
140
String JavaDoc assetString = request.getParameter("Asset_ID");
141         if (assetString == null || assetString.length() == 0)
142             return "";
143         int A_Asset_ID = 0;
144         try
145         {
146             A_Asset_ID = Integer.parseInt (assetString);
147         }
148         catch (NumberFormatException JavaDoc ex)
149         {
150             log.debug("streamAsset - " + ex);
151         }
152         if (A_Asset_ID == 0)
153         {
154             log.debug("streamAsset - no ID)");
155             return "No Asset ID";
156         }
157
158         // Get Asset
159
Properties ctx = JSPEnv.getCtx(request);
160         HttpSession session = request.getSession(true);
161         MAsset asset = new MAsset(ctx, A_Asset_ID);
162         if (asset.getA_Asset_ID() != A_Asset_ID)
163         {
164             log.debug("streamInvoice - Asset not found - ID=" + A_Asset_ID);
165             return "Asset not found";
166         }
167         // Get WebUser & Compare with invoice
168
WebUser wu = (WebUser)session.getAttribute(WebUser.NAME);
169         if (wu.getC_BPartner_ID() != asset.getC_BPartner_ID())
170         {
171             log.warn ("streamInvoice - Asset from BPartner - A_Asset_ID="
172                 + A_Asset_ID + " - BP_Invoice=" + asset.getC_BPartner_ID()
173                 + " = BP_User=" + wu.getC_BPartner_ID());
174             return "Your asset not found";
175         }
176         if (!asset.isDownloadable())
177             return "Asset not downloadable";
178
179         InputStream in = asset.getDownloadStream(ctx.getProperty(JSPEnv.CTX_DOCUMENT_DIR));
180         if (in == null)
181             return "Asset not found";
182
183         // Send File
184
MAsset_Delivery ad = new MAsset_Delivery (asset, request, wu.getAD_User_ID());
185         float speed = 0;
186         try
187         {
188             response.setContentType("application/zip");
189             response.setHeader("Content-Location", "asset.zip");
190             int length = 2048; // 2k Buffer
191
response.setBufferSize(length);
192         // response.setContentLength(length);
193
//
194
log.debug("streamAsset - " + in + ", available=" + in.available());
195             long time = System.currentTimeMillis();
196             //
197
StringBuffer JavaDoc content = new StringBuffer JavaDoc(asset.getDownloadName())
198                 .append("\n\rDownload for ")
199                 .append(wu.getName()).append(" - ").append(wu.getEmail())
200                 .append("\n\rVersion = ").append(asset.getVersionNo());
201             if (asset.getLot() != null && asset.getLot().length() > 0)
202                 content.append("\n\rLot = ").append(asset.getLot());
203             if (asset.getSerNo() != null && asset.getSerNo().length() > 0)
204                 content.append("\n\rSerNo = ").append(asset.getSerNo());
205             content.append("\n\rGuarantee Date = ").append(asset.getGuaranteeDate())
206                 .append("\n\r\n\rThanks for using Compiere Customer Asset Management");
207             //
208
ServletOutputStream out = response.getOutputStream ();
209             ZipOutputStream zip = new ZipOutputStream(out);
210             zip.setMethod(ZipOutputStream.DEFLATED);
211             zip.setLevel(Deflater.BEST_COMPRESSION);
212             zip.setComment(content.toString());
213             // Readme
214
ZipEntry entry = new ZipEntry("readme.txt");
215             zip.putNextEntry(entry);
216             zip.write(content.toString().getBytes(), 0, content.length());
217             zip.closeEntry();
218             // Payload
219
entry = new ZipEntry(asset.getDownloadName());
220             zip.putNextEntry(entry);
221             byte[] buffer = new byte[length];
222             int count = 0;
223             int totalSize = 0;
224             do
225             {
226                 count = in.read(buffer, 0, length);
227                 if (count > 0)
228                 {
229                     totalSize += count;
230                     zip.write (buffer, 0, count);
231                 }
232             } while (count != -1);
233             zip.closeEntry();
234             //
235
zip.finish();
236             zip.close();
237             //
238
in.close();
239             time = System.currentTimeMillis() - time;
240             speed = ((float)totalSize/1024) / ((float)time/1000);
241             log.debug("streamAsset - " + totalSize + " B - " + time + " ms - " + speed + " kB/sec");
242             // Delivery Record
243
ad.setDeliveryConfirmation(String.valueOf(speed));
244             ad.save();
245         }
246         catch (IOException ex)
247         {
248             log.error("streamAsset - " + ex);
249             // Delivery Record
250
try
251             {
252                 String JavaDoc msg = ex.getMessage ();
253                 if (msg == null || msg.length () == 0)
254                     msg = ex.toString ();
255                 if (msg.length () > 120)
256                     msg = msg.substring (0, 119);
257                 ad.setDeliveryConfirmation (msg);
258                 ad.save ();
259             }
260             catch (Exception JavaDoc ex1)
261             {
262                 log.error("streamAsset 2 - " + ex);
263             }
264             return "Streaming error";
265         }
266         //
267
return null;
268     } // streamAsset
269

270 } // AssetServlet
271
Popular Tags