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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
24 package org.collectionspace.services.report.nuxeo;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.InputStream;
31 import java.nio.file.Files;
32 import java.sql.Connection;
33 import java.sql.SQLException;
34 import java.util.HashMap;
35 import java.util.List;
38 import javax.ws.rs.core.MediaType;
39 import javax.naming.NamingException;
40 import javax.ws.rs.core.Response;
42 import net.sf.jasperreports.engine.JRException;
43 import net.sf.jasperreports.engine.JRExporter;
44 import net.sf.jasperreports.engine.JRExporterParameter;
45 import net.sf.jasperreports.engine.JRParameter;
46 import net.sf.jasperreports.engine.JasperCompileManager;
47 import net.sf.jasperreports.engine.JasperFillManager;
48 import net.sf.jasperreports.engine.JasperPrint;
49 import net.sf.jasperreports.engine.export.JRCsvExporter;
50 import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
51 import net.sf.jasperreports.engine.export.JRHtmlExporter;
52 import net.sf.jasperreports.engine.export.JRPdfExporter;
53 import net.sf.jasperreports.engine.export.JRXmlExporter;
54 import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
55 import net.sf.jasperreports.engine.export.ooxml.JRPptxExporter;
56 import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
58 import org.collectionspace.services.ReportJAXBSchema;
59 import org.collectionspace.services.report.ReportsCommon;
60 import org.collectionspace.services.client.PoxPayloadIn;
61 import org.collectionspace.services.client.PoxPayloadOut;
62 import org.collectionspace.services.client.ReportClient;
63 import org.collectionspace.services.common.CSWebApplicationException;
64 import org.collectionspace.services.common.ServiceMain;
65 import org.collectionspace.services.common.api.JEEServerDeployment;
66 import org.collectionspace.services.common.api.FileTools;
67 import org.collectionspace.services.common.api.Tools;
68 import org.collectionspace.services.common.context.ServiceContext;
69 import org.collectionspace.services.common.document.BadRequestException;
70 import org.collectionspace.services.common.document.DocumentException;
71 import org.collectionspace.services.common.document.DocumentWrapper;
72 import org.collectionspace.services.common.invocable.Invocable;
73 import org.collectionspace.services.common.invocable.InvocationContext;
74 import org.collectionspace.services.common.storage.JDBCTools;
75 import org.collectionspace.services.jaxb.InvocableJAXBSchema;
76 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
77 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
78 import org.collectionspace.services.nuxeo.client.java.NuxeoRepositoryClientImpl;
79 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
80 import org.jfree.util.Log;
81 import org.nuxeo.ecm.core.api.DocumentModel;
82 import org.nuxeo.ecm.core.api.model.PropertyException;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * ReportDocumentModelHandler
89 * $LastChangedRevision: $
92 public class ReportDocumentModelHandler extends NuxeoDocumentModelHandler<ReportsCommon> {
93 private final Logger logger = LoggerFactory.getLogger(ReportDocumentModelHandler.class);
94 private static String REPORTS_FOLDER = "reports";
95 private static String CSID_LIST_SEPARATOR = ",";
97 private static String REPORTS_STD_CSID_PARAM = "csid";
98 private static String REPORTS_STD_GROUPCSID_PARAM = "groupcsid";
99 private static String REPORTS_STD_CSIDLIST_PARAM = "csidlist";
100 private static String REPORTS_STD_TENANTID_PARAM = "tenantid";
102 public InputStream invokeReport(
103 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
105 InvocationContext invContext,
106 StringBuffer outMimeType,
107 StringBuffer outReportFileName) throws Exception {
108 CoreSessionInterface repoSession = null;
109 boolean releaseRepoSession = false;
111 String invocationMode = invContext.getMode();
112 String modeProperty = null;
113 HashMap<String, Object> params = new HashMap<String, Object>();
114 params.put(REPORTS_STD_TENANTID_PARAM, ctx.getTenantId());
115 boolean checkDocType = true;
117 // Note we set before we put in the default ones, so they cannot override tenant or CSID.
118 setParamsFromContext(params, invContext);
120 if(Invocable.INVOCATION_MODE_SINGLE.equalsIgnoreCase(invocationMode)) {
121 modeProperty = InvocableJAXBSchema.SUPPORTS_SINGLE_DOC;
122 params.put(REPORTS_STD_CSID_PARAM, invContext.getSingleCSID());
123 } else if(Invocable.INVOCATION_MODE_LIST.equalsIgnoreCase(invocationMode)) {
124 modeProperty = InvocableJAXBSchema.SUPPORTS_DOC_LIST;
125 List<String> csids = null;
126 InvocationContext.ListCSIDs listThing = invContext.getListCSIDs();
127 if (listThing!=null) {
128 csids = listThing.getCsid();
130 if (csids==null||csids.isEmpty()){
131 throw new BadRequestException(
132 "ReportResource: Report invoked in list mode, with no csids in list." );
134 StringBuilder sb = new StringBuilder();
135 boolean first = true;
136 for(String csidItem : csids) {
140 sb.append(CSID_LIST_SEPARATOR);
143 params.put(REPORTS_STD_CSIDLIST_PARAM, sb.toString());
144 } else if(Invocable.INVOCATION_MODE_GROUP.equalsIgnoreCase(invocationMode)) {
145 modeProperty = InvocableJAXBSchema.SUPPORTS_GROUP;
146 params.put(REPORTS_STD_GROUPCSID_PARAM, invContext.getGroupCSID());
147 } else if(Invocable.INVOCATION_MODE_NO_CONTEXT.equalsIgnoreCase(invocationMode)) {
148 modeProperty = InvocableJAXBSchema.SUPPORTS_NO_CONTEXT;
149 checkDocType = false;
151 throw new BadRequestException("ReportResource: unknown Invocation Mode: "
155 NuxeoRepositoryClientImpl repoClient = (NuxeoRepositoryClientImpl)this.getRepositoryClient(ctx);
156 repoSession = this.getRepositorySession();
157 if (repoSession == null) {
158 repoSession = repoClient.getRepositorySession(ctx);
159 releaseRepoSession = true;
162 // Get properties from the batch docModel, and release the session
163 String reportFileNameProperty;
165 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, csid);
166 DocumentModel docModel = wrapper.getWrappedObject();
167 Boolean supports = (Boolean) NuxeoUtils.getProperyValue(docModel, modeProperty); //docModel.getPropertyValue(modeProperty);
168 if(supports == null || !supports) {
169 throw new BadRequestException(
170 "ReportResource: This Report does not support Invocation Mode: "
174 List<String> forDocTypeList =
175 (List<String>) NuxeoUtils.getProperyValue(docModel, InvocableJAXBSchema.FOR_DOC_TYPES); //docModel.getPropertyValue(InvocableJAXBSchema.FOR_DOC_TYPES);
176 if (forDocTypeList==null || !forDocTypeList.contains(invContext.getDocType())) {
177 throw new BadRequestException(
178 "ReportResource: Invoked with unsupported document type: "
179 +invContext.getDocType());
182 reportFileNameProperty = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.FILENAME); //docModel.getPropertyValue(ReportJAXBSchema.FILENAME)); // Set the outgoing param with the report file name
184 // If the invocation context contains a MIME type then use it. Otherwise, look in the report resource. If no MIME type in the report resource,
185 // use the default MIME type.
187 if (!Tools.isEmpty(invContext.getOutputMIME())) {
188 outMimeType.append(invContext.getOutputMIME());
190 if (outMimeType == null || Tools.isEmpty(outMimeType.toString())) {
191 String reportOutputMime = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.OUTPUT_MIME); //docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
192 if (!Tools.isEmpty(reportOutputMime)) {
193 outMimeType.append(reportOutputMime);
195 outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
198 } catch (PropertyException pe) {
199 if (logger.isDebugEnabled()) {
200 logger.debug("Property exception getting batch values: ", pe);
203 } catch (DocumentException de) {
204 if (logger.isDebugEnabled()) {
205 logger.debug("Problem getting batch doc: ", de);
208 } catch (Exception e) {
209 if (logger.isDebugEnabled()) {
210 logger.debug("Caught exception ", e);
212 throw new DocumentException(e);
214 if (releaseRepoSession && repoSession != null) {
215 repoClient.releaseRepositorySession(ctx, repoSession);
219 return buildReportResult(csid, params, reportFileNameProperty, outMimeType.toString(), outReportFileName);
222 private void setParamsFromContext(Map<String, Object> params, InvocationContext invContext) {
223 InvocationContext.Params icParams = invContext.getParams();
224 if(icParams!= null) {
225 List<InvocationContext.Params.Param> icParamList = icParams.getParam();
226 if(icParamList != null) {
227 for(InvocationContext.Params.Param param:icParamList) {
228 String key = param.getKey();
229 String value = param.getValue();
230 if(!Tools.isEmpty(key) && !Tools.isEmpty(value)) {
231 params.put(key, value);
239 private InputStream buildReportResult(String reportCSID,
240 HashMap<String, Object> params, String reportFileName, String outputMimeType, StringBuffer outReportFileName)
242 Connection conn = null;
243 InputStream result = null;
246 String fileNameBase = Tools.getFilenameBase(reportFileName);
247 String compiledReportFilename = fileNameBase+ReportClient.COMPILED_REPORT_EXTENSION;
248 String reportDescriptionFilename = fileNameBase+ReportClient.REPORT_DECSRIPTION_EXTENSION;
250 String basePath = ServiceMain.getInstance().getServerRootDir() +
251 File.separator + JEEServerDeployment.CSPACE_DIR_NAME +
252 File.separator + REPORTS_FOLDER +
253 // File.separator + tenantName +
254 File.separator; // + reportFileName;
256 String compiledFilePath = basePath+compiledReportFilename;
257 File f = new File(compiledFilePath);
258 if(!f.exists()) { // Need to compile the file
259 // First verify that there is a source file.
260 String sourceFilePath = basePath+reportDescriptionFilename;
261 File f2 = new File(sourceFilePath);
262 if(!f2.exists()) { // Missing source file - error!
263 logger.error("Report for csid={} is missing the specified source file: {}",
264 reportCSID, sourceFilePath);
265 throw new RuntimeException("Report is missing the specified source file!");
267 logger.info("Report for csid={} is not compiled. Compiling first, and saving to: {}",
268 reportCSID, compiledFilePath);
269 JasperCompileManager.compileReportToFile(sourceFilePath, compiledFilePath);
272 conn = getConnection();
274 if (logger.isTraceEnabled()) {
275 logger.trace("ReportResource for csid=" + reportCSID
276 +" output as "+outputMimeType+" using report file: "+compiledFilePath);
278 FileInputStream fileStream = new FileInputStream(compiledFilePath);
280 // export report to pdf and build a response with the bytes
281 //JasperExportManager.exportReportToPdf(jasperprint);
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(".");
289 outputFilename = outputFilename.substring(0, idx);
290 // Strip any sub-dir from report filename.
291 idx = outputFilename.lastIndexOf(File.separator);
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";
327 logger.error("Reporting: unsupported output MIME type - defaulting to PDF");
328 exporter = new JRPdfExporter();
329 outputFilename = outputFilename+"-default-to.pdf";
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());
338 JasperPrint jasperPrint = JasperFillManager.fillReport(fileStream, params,conn);
340 // Report will be to a temporary file.
341 File tempOutputFile = Files.createTempFile("report-", null).toFile();
342 FileOutputStream tempOutputStream = new FileOutputStream(tempOutputFile);
343 exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
344 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, tempOutputStream);
345 exporter.exportReport();
346 tempOutputStream.close();
348 result = new FileInputStream(tempOutputFile);
350 } catch (SQLException sqle) {
351 // SQLExceptions can be chained. We have at least one exception, so
352 // set up a loop to make sure we let the user know about all of them
353 // if there happens to be more than one.
354 if (logger.isDebugEnabled()) {
355 SQLException tempException = sqle;
356 while (null != tempException) {
357 logger.debug("SQL Exception: " + sqle.getLocalizedMessage());
359 // loop to the next exception
360 tempException = tempException.getNextException();
363 Response response = Response.status(
364 Response.Status.INTERNAL_SERVER_ERROR).entity(
365 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
366 throw new CSWebApplicationException(sqle, response);
367 } catch (JRException jre) {
368 if (logger.isDebugEnabled()) {
369 logger.debug("JR Exception: " + jre.getLocalizedMessage() + " Cause: "+jre.getCause());
371 Response response = Response.status(
372 Response.Status.INTERNAL_SERVER_ERROR).entity(
373 "Invoke failed (Jasper problem) on Report csid=" + reportCSID).type("text/plain").build();
374 throw new CSWebApplicationException(jre, response);
375 } catch (FileNotFoundException fnfe) {
376 if (logger.isDebugEnabled()) {
377 logger.debug("FileNotFoundException: " + fnfe.getLocalizedMessage());
379 Response response = Response.status(
380 Response.Status.INTERNAL_SERVER_ERROR).entity(
381 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
382 throw new CSWebApplicationException(fnfe, response);
387 } catch (SQLException sqle) {
388 // SQLExceptions can be chained. We have at least one exception, so
389 // set up a loop to make sure we let the user know about all of them
390 // if there happens to be more than one.
391 if (logger.isDebugEnabled()) {
392 logger.debug("SQL Exception closing connection: "
393 + sqle.getLocalizedMessage());
395 } catch (Exception e) {
396 if (logger.isDebugEnabled()) {
397 logger.debug("Exception closing connection", e);
404 private Connection getConnection() throws NamingException, SQLException {
405 Connection result = null;
407 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
409 String repositoryName = ctx.getRepositoryName();
410 if (repositoryName != null && repositoryName.trim().isEmpty() == false) {
411 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
412 String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId);
413 result = JDBCTools.getConnection(JDBCTools.NUXEO_READER_DATASOURCE_NAME, databaseName);
415 } catch (Exception e) {
417 throw new NamingException();