a03c9539f3c00405c6f370c3333667493e11da94
[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  * 
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
145                 try(InputStream is = new BufferedInputStream(new FileInputStream(inFile));
146                         OutputStream os = new BufferedOutputStream(response.getOutputStream());) {
147                         response.reset();
148                         response.setContentLength((int) inFile.length());
149                         response.setContentType("application/octet-stream");
150                         response.setHeader("Content-disposition", "attachment; filename=\""
151                                         + inFile.getName() + "\"");
152                         copyStream(is, os);
153                         os.flush();
154                 } catch (Exception ex) {
155                         throw new Exception("Could not open input or output stream for file ");
156                 }
157         }
158
159         private void serveFile(HttpServletResponse response, byte[] outStream,
160                         String name) throws Exception {
161                 OutputStream os = null;
162                 InputStream is = null;
163                 try {
164                         response.reset();
165                         response.setContentLength((int) outStream.length);
166                         response.setContentType("application/octet-stream");
167                         response.setHeader("Content-disposition", "attachment; filename=\""
168                                         +  ESAPI.encoder().canonicalize(name) + "\"");
169                         copyStream(response, outStream);
170                 } catch (Exception ex) {
171                         if (os == null)
172                                 throw new Exception("Could not open output stream for file ");
173                         if (is == null)
174                                 throw new Exception("Could not open input stream for file ");
175                 } finally {
176                         if (os != null) {
177                                 os.close();
178                         }
179                         if (is != null)
180                                 is.close();
181                 }
182         }
183
184         private int copyStream(InputStream in, OutputStream out) throws IOException {
185                 int bytes, totalBytes = 0;
186
187                 byte[] b = new byte[4096];
188
189                 while ((bytes = in.read(b, 0, b.length)) != -1) {
190                         totalBytes += bytes;
191                         out.write(b, 0, bytes);
192                 }
193                 return totalBytes;
194         }
195
196         private int copyStream(HttpServletResponse response, byte[] outStream)
197                         throws IOException {
198                 
199                 OutputStream os = new BufferedOutputStream(response.getOutputStream());
200                 os.write(outStream);
201                 os.flush();
202                 return outStream.length;
203         }
204
205         public DataAccessService getDataAccessService() {
206                 return dataAccessService;
207         }
208
209         public void setDataAccessService(DataAccessService dataAccessService) {
210                 this.dataAccessService = dataAccessService;
211         }
212
213 }