]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ecd7764db177ce38f39e43559ef5e2801eb0ed2a
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.report.nuxeo;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.FileNotFoundException;
31 import java.io.InputStream;
32 import java.sql.Connection;
33 import java.sql.SQLException;
34 import java.util.HashMap;
35 import java.util.List;
36 import java.util.Map;
37
38 import javax.ws.rs.core.MediaType;
39 import javax.naming.NamingException;
40 import javax.ws.rs.WebApplicationException;
41 import javax.ws.rs.core.Response;
42
43 import net.sf.jasperreports.engine.JRException;
44 import net.sf.jasperreports.engine.JRExporter;
45 import net.sf.jasperreports.engine.JRExporterParameter;
46 import net.sf.jasperreports.engine.JRParameter;
47 import net.sf.jasperreports.engine.JasperCompileManager;
48 import net.sf.jasperreports.engine.JasperExportManager;
49 import net.sf.jasperreports.engine.JasperFillManager;
50 import net.sf.jasperreports.engine.JasperPrint;
51 import net.sf.jasperreports.engine.export.JRCsvExporter;
52 import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
53 import net.sf.jasperreports.engine.export.JRHtmlExporter;
54 import net.sf.jasperreports.engine.export.JRPdfExporter;
55 import net.sf.jasperreports.engine.export.JRXmlExporter;
56 import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
57 import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
58 import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
59
60 import org.bouncycastle.crypto.RuntimeCryptoException;
61 import org.collectionspace.services.ReportJAXBSchema;
62 import org.collectionspace.services.report.ReportsCommon;
63 import org.collectionspace.services.client.PoxPayloadIn;
64 import org.collectionspace.services.client.PoxPayloadOut;
65 import org.collectionspace.services.client.ReportClient;
66 import org.collectionspace.services.common.CSWebApplicationException;
67 import org.collectionspace.services.common.ServiceMain;
68 import org.collectionspace.services.common.api.JEEServerDeployment;
69 import org.collectionspace.services.common.api.FileTools;
70 import org.collectionspace.services.common.api.Tools;
71 import org.collectionspace.services.common.config.ConfigReader;
72 import org.collectionspace.services.common.context.ServiceContext;
73 import org.collectionspace.services.common.document.BadRequestException;
74 import org.collectionspace.services.common.document.DocumentException;
75 import org.collectionspace.services.common.document.DocumentWrapper;
76 import org.collectionspace.services.common.invocable.Invocable;
77 import org.collectionspace.services.common.invocable.InvocationContext;
78 import org.collectionspace.services.common.storage.JDBCTools;
79 import org.collectionspace.services.jaxb.InvocableJAXBSchema;
80 import org.collectionspace.services.nuxeo.client.java.DocHandlerBase;
81 import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface;
82 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
83 import org.jfree.util.Log;
84 import org.nuxeo.ecm.core.api.DocumentModel;
85 import org.nuxeo.ecm.core.api.model.PropertyException;
86 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89
90 /**
91  * ReportDocumentModelHandler
92  *
93  * $LastChangedRevision: $
94  * $LastChangedDate: $
95  */
96 public class ReportDocumentModelHandler extends DocHandlerBase<ReportsCommon> {
97     private final Logger logger = LoggerFactory.getLogger(ReportDocumentModelHandler.class);
98     private static String REPORTS_FOLDER = "reports";
99     private static String CSID_LIST_SEPARATOR = ",";
100     
101     private static String REPORTS_STD_CSID_PARAM = "csid";
102     private static String REPORTS_STD_GROUPCSID_PARAM = "groupcsid";
103     private static String REPORTS_STD_CSIDLIST_PARAM = "csidlist";
104     private static String REPORTS_STD_TENANTID_PARAM = "tenantid";
105         
106         public InputStream invokeReport(
107                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
108                         String csid,
109                         InvocationContext invContext,
110                         StringBuffer outMimeType,
111                         StringBuffer outReportFileName) throws Exception {
112                 RepositoryInstanceInterface repoSession = null;
113                 boolean releaseRepoSession = false;
114
115                 String invocationMode = invContext.getMode();
116                 String modeProperty = null;
117                 HashMap<String, Object> params = new HashMap<String, Object>();
118                 params.put(REPORTS_STD_TENANTID_PARAM, ctx.getTenantId());
119                 boolean checkDocType = true;
120                 
121                 // Note we set before we put in the default ones, so they cannot override tenant or CSID.
122                 setParamsFromContext(params, invContext);
123                 
124                 if(Invocable.INVOCATION_MODE_SINGLE.equalsIgnoreCase(invocationMode)) {
125                         modeProperty = InvocableJAXBSchema.SUPPORTS_SINGLE_DOC;
126                 params.put(REPORTS_STD_CSID_PARAM, invContext.getSingleCSID());
127                 } else if(Invocable.INVOCATION_MODE_LIST.equalsIgnoreCase(invocationMode)) {
128                         modeProperty = InvocableJAXBSchema.SUPPORTS_DOC_LIST;
129                         List<String> csids = null;
130                         InvocationContext.ListCSIDs listThing = invContext.getListCSIDs();
131                                 if(listThing!=null) {
132                                         csids = listThing.getCsid();
133                                 }
134                                 if(csids==null||csids.isEmpty()){
135                                 throw new BadRequestException(
136                                                 "ReportResource: Report invoked in list mode, with no csids in list." );
137                                 }
138                                 StringBuilder sb = new StringBuilder();
139                                 boolean first = true;
140                                 for(String csidItem : csids) {
141                                         if(first)
142                                                 first = false;
143                                         else
144                                                 sb.append(CSID_LIST_SEPARATOR);
145                                         sb.append(csidItem);
146                                 }
147                 params.put(REPORTS_STD_CSIDLIST_PARAM, sb.toString());
148                 } else if(Invocable.INVOCATION_MODE_GROUP.equalsIgnoreCase(invocationMode)) {
149                         modeProperty = InvocableJAXBSchema.SUPPORTS_GROUP;
150                 params.put(REPORTS_STD_GROUPCSID_PARAM, invContext.getGroupCSID());
151                 } else if(Invocable.INVOCATION_MODE_NO_CONTEXT.equalsIgnoreCase(invocationMode)) {
152                         modeProperty = InvocableJAXBSchema.SUPPORTS_NO_CONTEXT;
153                         checkDocType = false;
154                 } else {
155                         throw new BadRequestException("ReportResource: unknown Invocation Mode: "
156                                 +invocationMode);
157                 }
158                 
159                 
160                 RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(ctx);
161                 repoSession = this.getRepositorySession();
162                 if (repoSession == null) {
163                         repoSession = repoClient.getRepositorySession(ctx);
164                         releaseRepoSession = true;
165                 }
166
167                 // Get properties from the batch docModel, and release the session
168                 String reportFileNameProperty;
169                 try {
170                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, csid);
171                         DocumentModel docModel = wrapper.getWrappedObject();
172                         Boolean supports = (Boolean)docModel.getPropertyValue(modeProperty);
173                         if(supports == null || !supports) {
174                                 throw new BadRequestException(
175                                                 "ReportResource: This Report does not support Invocation Mode: "
176                                         +invocationMode);
177                         }
178                 if(checkDocType) {
179                         List<String> forDocTypeList = 
180                                 (List<String>)docModel.getPropertyValue(InvocableJAXBSchema.FOR_DOC_TYPES);
181                         if(forDocTypeList==null
182                                         || !forDocTypeList.contains(invContext.getDocType())) {
183                                 throw new BadRequestException(
184                                                 "ReportResource: Invoked with unsupported document type: "
185                                                 +invContext.getDocType());
186                         }
187                 }
188                 reportFileNameProperty = ((String)docModel.getPropertyValue(ReportJAXBSchema.FILENAME)); // Set the outgoing param with the report file name
189                         String reportOutputMime = (String)docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
190                         if(!Tools.isEmpty(reportOutputMime)) {
191                                 outMimeType.append(reportOutputMime);
192                         } else {
193                                 outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
194                         }
195                 } catch (PropertyException pe) {
196                         if (logger.isDebugEnabled()) {
197                                 logger.debug("Property exception getting batch values: ", pe);
198                         }
199                         throw pe;
200                 } catch (DocumentException de) {
201                         if (logger.isDebugEnabled()) {
202                                 logger.debug("Problem getting batch doc: ", de);
203                         }
204                         throw de;
205                 } catch (Exception e) {
206                         if (logger.isDebugEnabled()) {
207                                 logger.debug("Caught exception ", e);
208                         }
209                         throw new DocumentException(e);
210                 } finally {
211                         if (releaseRepoSession && repoSession != null) {
212                                 repoClient.releaseRepositorySession(ctx, repoSession);
213                         }
214                 }
215                 
216         return buildReportResult(csid, params, reportFileNameProperty, outMimeType.toString(), outReportFileName);
217         }
218         
219         private void setParamsFromContext(Map<String, Object> params, InvocationContext invContext) {
220                 InvocationContext.Params icParams = invContext.getParams();
221                 if(icParams!= null) {
222                         List<InvocationContext.Params.Param> icParamList = icParams.getParam();
223                         if(icParamList != null) {
224                                 for(InvocationContext.Params.Param param:icParamList) {
225                                         String key = param.getKey();
226                                         String value = param.getValue();
227                                         if(!Tools.isEmpty(key) && !Tools.isEmpty(value)) {
228                                                 params.put(key, value);
229                                         }
230                                 }
231                         }
232                 }
233                 
234         }
235
236     private InputStream buildReportResult(String reportCSID, 
237                 HashMap<String, Object> params, String reportFileName, String outputMimeType, StringBuffer outReportFileName)
238                                 throws Exception {
239                 Connection conn = null;
240                 InputStream result = null;
241                 
242         try {
243                 String fileNameBase = Tools.getFilenameBase(reportFileName);
244                 String compiledReportFilename = fileNameBase+ReportClient.COMPILED_REPORT_EXTENSION;
245                 String reportDescriptionFilename = fileNameBase+ReportClient.REPORT_DECSRIPTION_EXTENSION;
246                 
247                         String basePath = ServiceMain.getInstance().getServerRootDir() +
248                                                                 File.separator + JEEServerDeployment.CSPACE_DIR_NAME + 
249                                                                 File.separator + REPORTS_FOLDER +
250                                                                 // File.separator + tenantName +
251                                                                 File.separator; // + reportFileName;
252                         
253                         String compiledFilePath = basePath+compiledReportFilename; 
254                         File f = new File(compiledFilePath);
255                         if(!f.exists()) { // Need to compile the file
256                                 // First verify that there is a source file.
257                                 String sourceFilePath = basePath+reportDescriptionFilename; 
258                                 File f2 = new File(sourceFilePath);
259                                 if(!f2.exists()) { // Missing source file - error!
260                                         logger.error("Report for csid={} is missing the specified source file: {}",
261                                                                         reportCSID, sourceFilePath);
262                                         throw new RuntimeException("Report is missing the specified source file!");
263                                 }
264                 logger.info("Report for csid={} is not compiled. Compiling first, and saving to: {}",
265                                 reportCSID, compiledFilePath);
266                 JasperCompileManager.compileReportToFile(sourceFilePath, compiledFilePath);
267                         }                               
268                                 
269                         conn = getConnection();
270         
271             if (logger.isTraceEnabled()) {
272                 logger.trace("ReportResource for csid=" + reportCSID
273                                 +" output as "+outputMimeType+" using report file: "+compiledFilePath);
274             }
275                         FileInputStream fileStream = new FileInputStream(compiledFilePath);
276         
277                         // export report to pdf and build a response with the bytes
278                         //JasperExportManager.exportReportToPdf(jasperprint);
279                         
280                         // Report will be to a byte output array.
281                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
282
283                         JRExporter exporter = null;
284                         // Strip extension from report filename.
285                         String outputFilename = reportFileName;
286                         // Strip extension from report filename.
287                         int idx = outputFilename.lastIndexOf("."); 
288                         if(idx>0)
289                                 outputFilename = outputFilename.substring(0, idx);
290                         // Strip any sub-dir from report filename.
291                         idx = outputFilename.lastIndexOf(File.separator); 
292                         if(idx>0)
293                                 outputFilename = outputFilename.substring(idx+1);
294                         if(outputMimeType.equals(MediaType.APPLICATION_XML)) {
295                                 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
296                                 exporter = new JRXmlExporter();
297                                 outputFilename = outputFilename+".xml";
298                         } else if(outputMimeType.equals(MediaType.TEXT_HTML)) {
299                                 exporter = new JRHtmlExporter();
300                                 outputFilename = outputFilename+".html";
301                         } else if(outputMimeType.equals(ReportClient.PDF_MIME_TYPE)) {
302                                 exporter = new JRPdfExporter();
303                                 outputFilename = outputFilename+".pdf";
304                         } else if(outputMimeType.equals(ReportClient.CSV_MIME_TYPE)) {
305                                 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
306                                 exporter = new JRCsvExporter();
307                                 exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, ",");
308                                 outputFilename = outputFilename+".csv";
309                         } else if(outputMimeType.equals(ReportClient.TSV_MIME_TYPE)) {
310                                 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
311                                 exporter = new JRCsvExporter();
312                                 exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, "\t");
313                                 outputFilename = outputFilename+".csv";
314                         } else if(outputMimeType.equals(ReportClient.MSWORD_MIME_TYPE)  // Understand msword as docx
315                                         || outputMimeType.equals(ReportClient.OPEN_DOCX_MIME_TYPE)) {
316                                 exporter = new JRDocxExporter();
317                                 outputFilename = outputFilename+".docx";
318                         } else if(outputMimeType.equals(ReportClient.MSEXCEL_MIME_TYPE) // Understand msexcel as xlsx
319                                         || outputMimeType.equals(ReportClient.OPEN_XLSX_MIME_TYPE)) {
320                                 exporter = new JRXlsxExporter();
321                                 outputFilename = outputFilename+".xlsx";
322                         } else if(outputMimeType.equals(ReportClient.MSPPT_MIME_TYPE)   // Understand msppt as xlsx
323                                         || outputMimeType.equals(ReportClient.OPEN_PPTX_MIME_TYPE)) {
324                                 exporter = new JRPptxExporter();
325                                 outputFilename = outputFilename+".pptx";
326                         } else {
327                                 logger.error("Reporting: unsupported output MIME type - defaulting to PDF");
328                                 exporter = new JRPdfExporter();
329                                 outputFilename = outputFilename+"-default-to.pdf";
330                         }
331                         outReportFileName.append(outputFilename); // Set the out going param to the report's final file name
332                         // FIXME: Logging temporarily set to INFO level for CSPACE-5766;
333                         // can change to TRACE or DEBUG level as warranted thereafter
334                         if (logger.isInfoEnabled()) {
335                             logger.info(FileTools.getJavaTmpDirInfo());
336                         }
337                         // fill the report
338                         JasperPrint jasperPrint = JasperFillManager.fillReport(fileStream, params,conn);
339                                 
340                         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
341                         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
342                         exporter.exportReport();
343                         result = new ByteArrayInputStream(baos.toByteArray());
344         
345                 return result;
346         } catch (SQLException sqle) {
347             // SQLExceptions can be chained. We have at least one exception, so
348             // set up a loop to make sure we let the user know about all of them
349             // if there happens to be more than one.
350             if (logger.isDebugEnabled()) {
351                     SQLException tempException = sqle;
352                     while (null != tempException) {
353                                 logger.debug("SQL Exception: " + sqle.getLocalizedMessage());
354         
355                         // loop to the next exception
356                         tempException = tempException.getNextException();
357                     }
358             }
359             Response response = Response.status(
360                     Response.Status.INTERNAL_SERVER_ERROR).entity(
361                                 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
362             throw new CSWebApplicationException(sqle, response);
363         } catch (JRException jre) {
364             if (logger.isDebugEnabled()) {
365                 logger.debug("JR Exception: " + jre.getLocalizedMessage() + " Cause: "+jre.getCause());
366             }
367             Response response = Response.status(
368                     Response.Status.INTERNAL_SERVER_ERROR).entity(
369                                 "Invoke failed (Jasper problem) on Report csid=" + reportCSID).type("text/plain").build();
370             throw new CSWebApplicationException(jre, response);
371         } catch (FileNotFoundException fnfe) {
372             if (logger.isDebugEnabled()) {
373                 logger.debug("FileNotFoundException: " + fnfe.getLocalizedMessage());
374             }
375             Response response = Response.status(
376                     Response.Status.INTERNAL_SERVER_ERROR).entity(
377                                 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
378             throw new CSWebApplicationException(fnfe, response);
379                 } finally {
380                 if (conn!=null) {
381                         try {
382                                 conn.close();
383                 } catch (SQLException sqle) {
384                     // SQLExceptions can be chained. We have at least one exception, so
385                     // set up a loop to make sure we let the user know about all of them
386                     // if there happens to be more than one.
387                     if (logger.isDebugEnabled()) {
388                                 logger.debug("SQL Exception closing connection: " 
389                                                 + sqle.getLocalizedMessage());
390                     }
391                 } catch (Exception e) {
392                     if (logger.isDebugEnabled()) {
393                         logger.debug("Exception closing connection", e);
394                     }
395                 }
396                 }
397         }
398     }
399
400     private Connection getConnection() throws NamingException, SQLException {
401         Connection result = null;
402         
403         ServiceContext ctx = this.getServiceContext();
404         try {
405                 String repositoryName = ctx.getRepositoryName();
406                 if (repositoryName != null && repositoryName.trim().isEmpty() == false) {
407                         result = JDBCTools.getConnection(JDBCTools.NUXEO_DATASOURCE_NAME, repositoryName);
408                 }
409                 } catch (Exception e) {
410                         Log.error(e);
411                         throw new NamingException();
412                 }
413         
414         return result;
415     }
416
417 }
418