94ee29fd7ff89d30f0bb55bf2b422f6fbcf502b7
[portal/sdk.git] /
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalsdk.analytics.system.fusion.controller;
39 /**
40  * Raptor Blob Extract Servlet
41  * 
42  */
43
44 import java.io.BufferedInputStream;
45 import java.io.BufferedOutputStream;
46 import java.io.File;
47 import java.io.FileInputStream;
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.io.OutputStream;
51 import java.sql.Blob;
52 import java.util.HashMap;
53 import java.util.List;
54 import java.util.Map;
55
56 import javax.servlet.http.HttpServletRequest;
57 import javax.servlet.http.HttpServletResponse;
58
59 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
60 import org.onap.portalsdk.core.service.DataAccessService;
61 import org.owasp.esapi.ESAPI;
62 import org.springframework.web.servlet.ModelAndView;;
63
64
65 public class FileServletController  {
66
67         private static transient  final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FileServletController.class);
68
69         private DataAccessService dataAccessService;
70
71         public ModelAndView handleRequestInternal(HttpServletRequest request,
72                         HttpServletResponse response) throws Exception {
73                 logger.debug(EELFLoggerDelegate.debugLogger, ("FileServletController:: f=" + request.getParameter("f")));
74
75                 String fname = request.getParameter("f");
76
77                 try {
78                         Map params = new HashMap();
79                         params.put("fname", fname);
80
81                         logger.debug(EELFLoggerDelegate.debugLogger, ("executing query: select file_blob from cr_report_file_history where file_name = :"
82                                         + fname));
83
84                         List<Object> fileFromDB = (List<Object>) getDataAccessService().executeNamedQuery("getFileWithName", params, null);
85
86                         byte[] allBytesInBlob = null;
87
88                         if (fileFromDB != null && fileFromDB.size() > 0) {
89
90                                 logger.debug(EELFLoggerDelegate.debugLogger, ("reading file blob from DB..."));
91                                 try {
92                                         
93                             /*for weblogic setup
94                              * if(Globals.isWeblogicServer()) {
95                                 weblogic.jdbc.vendor.oracle.OracleThinBlob aBlob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) ((org.hibernate.lob.SerializableBlob) fileFromDB
96                                                                 .get(0)).getWrappedBlob();
97                                 InputStream inBlob = ((java.sql.Blob) aBlob).getBinaryStream();
98                                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
99                                 byte[] buf = new byte[1024];
100                                 int n = 0;
101                                 while ((n=inBlob.read(buf))>=0) {
102                                         baos.write(buf, 0, n);
103                                 }
104                                 inBlob.close();
105                                 allBytesInBlob = baos.toByteArray();
106                              } else { */
107                                         /* works in Hinernate3  [       oracle.sql.BLOB aBlob = (oracle.sql.BLOB) ((org.hibernate.lob.SerializableBlob) fileFromDB
108                                                                         .get(0)).getWrappedBlob();
109                                                         allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length()); ] */
110                             // }
111                                         
112                                         Object fileFromDBType = fileFromDB.get(0);
113                                         if(fileFromDBType instanceof byte[] ) // postgres
114                                                 allBytesInBlob = (byte[]) fileFromDB.get(0);
115                                         else if (fileFromDBType instanceof Blob ) // oracle
116                                                 allBytesInBlob = ((Blob) fileFromDB.get(0)).getBytes(1, (int) ((Blob) fileFromDB.get(0)).length());
117                                         
118                                         
119                                         
120                                 } catch (Exception e) {
121                                         logger.error(EELFLoggerDelegate.debugLogger, ("An exception has occurred: " + e.getMessage()));
122                                         throw (e);
123                                 }
124
125                         } else {
126                                 logger.error(EELFLoggerDelegate.debugLogger, ("ERROR: No BLOB returned from DB..."));
127                                 throw (new Exception("ERROR: No BLOB returned from DB..."));
128                         }
129
130                         serveFile(response, allBytesInBlob, fname);
131                         return null;
132                 } catch (Exception e) {
133                         logger.error(EELFLoggerDelegate.debugLogger, ("Exception occurred..." + e.getMessage()));
134                         Map<String, Object> errView = new HashMap<String, Object>();
135                         errView.put("error", "The requested resource was not found.");
136                         //return new ModelAndView(getExceptionView(), "model", errView);
137                         return null;
138                 }
139
140         }
141
142         private void serveFile(HttpServletResponse response, File inFile)
143                         throws Exception {
144                 OutputStream os = null;
145                 InputStream is = null;
146                 try {
147                         response.reset();
148                         is = new BufferedInputStream(new FileInputStream(inFile));
149                         os = new BufferedOutputStream(response.getOutputStream());
150                         response.setContentLength((int) inFile.length());
151                         response.setContentType("application/octet-stream");
152                         response.setHeader("Content-disposition", "attachment; filename=\""
153                                         + inFile.getName() + "\"");
154                         copyStream(is, os);
155                         os.flush();
156                 } catch (Exception ex) {
157                         if (os == null)
158                                 throw new Exception("Could not open output stream for file ");
159                         if (is == null)
160                                 throw new Exception("Could not open input stream for file ");
161                 } finally {
162                         if (os != null) {
163                                 os.close();
164                         }
165                         if (is != null)
166                                 is.close();
167                 }
168         }
169
170         private void serveFile(HttpServletResponse response, byte[] outStream,
171                         String name) throws Exception {
172                 OutputStream os = null;
173                 InputStream is = null;
174                 try {
175                         response.reset();
176                         response.setContentLength((int) outStream.length);
177                         response.setContentType("application/octet-stream");
178                         response.setHeader("Content-disposition", "attachment; filename=\""
179                                         +  ESAPI.encoder().canonicalize(name) + "\"");
180                         copyStream(response, outStream);
181                 } catch (Exception ex) {
182                         if (os == null)
183                                 throw new Exception("Could not open output stream for file ");
184                         if (is == null)
185                                 throw new Exception("Could not open input stream for file ");
186                 } finally {
187                         if (os != null) {
188                                 os.close();
189                         }
190                         if (is != null)
191                                 is.close();
192                 }
193         }
194
195         private int copyStream(InputStream in, OutputStream out) throws IOException {
196                 int bytes, totalBytes = 0;
197
198                 byte[] b = new byte[4096];
199
200                 while ((bytes = in.read(b, 0, b.length)) != -1) {
201                         totalBytes += bytes;
202                         out.write(b, 0, bytes);
203                 }
204                 return totalBytes;
205         }
206
207         private int copyStream(HttpServletResponse response, byte[] outStream)
208                         throws IOException {
209                 
210                 OutputStream os = new BufferedOutputStream(response.getOutputStream());
211                 os.write(outStream);
212                 os.flush();
213                 return outStream.length;
214         }
215
216         public DataAccessService getDataAccessService() {
217                 return dataAccessService;
218         }
219
220         public void setDataAccessService(DataAccessService dataAccessService) {
221                 this.dataAccessService = dataAccessService;
222         }
223
224 }