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;
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
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;
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.RepositoryJavaClientImpl;
79 import org.jfree.util.Log;
80 import org.nuxeo.ecm.core.api.DocumentModel;
81 import org.nuxeo.ecm.core.api.model.PropertyException;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
86 * ReportDocumentModelHandler
88 * $LastChangedRevision: $
91 public class ReportDocumentModelHandler extends NuxeoDocumentModelHandler<ReportsCommon> {
92 private final Logger logger = LoggerFactory.getLogger(ReportDocumentModelHandler.class);
93 private static String REPORTS_FOLDER = "reports";
94 private static String CSID_LIST_SEPARATOR = ",";
96 private static String REPORTS_STD_CSID_PARAM = "csid";
97 private static String REPORTS_STD_GROUPCSID_PARAM = "groupcsid";
98 private static String REPORTS_STD_CSIDLIST_PARAM = "csidlist";
99 private static String REPORTS_STD_TENANTID_PARAM = "tenantid";
101 public InputStream invokeReport(
102 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
104 InvocationContext invContext,
105 StringBuffer outMimeType,
106 StringBuffer outReportFileName) throws Exception {
107 CoreSessionInterface repoSession = null;
108 boolean releaseRepoSession = false;
110 String invocationMode = invContext.getMode();
111 String modeProperty = null;
112 HashMap<String, Object> params = new HashMap<String, Object>();
113 params.put(REPORTS_STD_TENANTID_PARAM, ctx.getTenantId());
114 boolean checkDocType = true;
116 // Note we set before we put in the default ones, so they cannot override tenant or CSID.
117 setParamsFromContext(params, invContext);
119 if(Invocable.INVOCATION_MODE_SINGLE.equalsIgnoreCase(invocationMode)) {
120 modeProperty = InvocableJAXBSchema.SUPPORTS_SINGLE_DOC;
121 params.put(REPORTS_STD_CSID_PARAM, invContext.getSingleCSID());
122 } else if(Invocable.INVOCATION_MODE_LIST.equalsIgnoreCase(invocationMode)) {
123 modeProperty = InvocableJAXBSchema.SUPPORTS_DOC_LIST;
124 List<String> csids = null;
125 InvocationContext.ListCSIDs listThing = invContext.getListCSIDs();
126 if(listThing!=null) {
127 csids = listThing.getCsid();
129 if(csids==null||csids.isEmpty()){
130 throw new BadRequestException(
131 "ReportResource: Report invoked in list mode, with no csids in list." );
133 StringBuilder sb = new StringBuilder();
134 boolean first = true;
135 for(String csidItem : csids) {
139 sb.append(CSID_LIST_SEPARATOR);
142 params.put(REPORTS_STD_CSIDLIST_PARAM, sb.toString());
143 } else if(Invocable.INVOCATION_MODE_GROUP.equalsIgnoreCase(invocationMode)) {
144 modeProperty = InvocableJAXBSchema.SUPPORTS_GROUP;
145 params.put(REPORTS_STD_GROUPCSID_PARAM, invContext.getGroupCSID());
146 } else if(Invocable.INVOCATION_MODE_NO_CONTEXT.equalsIgnoreCase(invocationMode)) {
147 modeProperty = InvocableJAXBSchema.SUPPORTS_NO_CONTEXT;
148 checkDocType = false;
150 throw new BadRequestException("ReportResource: unknown Invocation Mode: "
155 RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl)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)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>)docModel.getPropertyValue(InvocableJAXBSchema.FOR_DOC_TYPES);
176 if(forDocTypeList==null
177 || !forDocTypeList.contains(invContext.getDocType())) {
178 throw new BadRequestException(
179 "ReportResource: Invoked with unsupported document type: "
180 +invContext.getDocType());
183 reportFileNameProperty = ((String)docModel.getPropertyValue(ReportJAXBSchema.FILENAME)); // Set the outgoing param with the report file name
184 String reportOutputMime = (String)docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
185 if(!Tools.isEmpty(reportOutputMime)) {
186 outMimeType.append(reportOutputMime);
188 outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
190 } catch (PropertyException pe) {
191 if (logger.isDebugEnabled()) {
192 logger.debug("Property exception getting batch values: ", pe);
195 } catch (DocumentException de) {
196 if (logger.isDebugEnabled()) {
197 logger.debug("Problem getting batch doc: ", de);
200 } catch (Exception e) {
201 if (logger.isDebugEnabled()) {
202 logger.debug("Caught exception ", e);
204 throw new DocumentException(e);
206 if (releaseRepoSession && repoSession != null) {
207 repoClient.releaseRepositorySession(ctx, repoSession);
211 return buildReportResult(csid, params, reportFileNameProperty, outMimeType.toString(), outReportFileName);
214 private void setParamsFromContext(Map<String, Object> params, InvocationContext invContext) {
215 InvocationContext.Params icParams = invContext.getParams();
216 if(icParams!= null) {
217 List<InvocationContext.Params.Param> icParamList = icParams.getParam();
218 if(icParamList != null) {
219 for(InvocationContext.Params.Param param:icParamList) {
220 String key = param.getKey();
221 String value = param.getValue();
222 if(!Tools.isEmpty(key) && !Tools.isEmpty(value)) {
223 params.put(key, value);
231 private InputStream buildReportResult(String reportCSID,
232 HashMap<String, Object> params, String reportFileName, String outputMimeType, StringBuffer outReportFileName)
234 Connection conn = null;
235 InputStream result = null;
238 String fileNameBase = Tools.getFilenameBase(reportFileName);
239 String compiledReportFilename = fileNameBase+ReportClient.COMPILED_REPORT_EXTENSION;
240 String reportDescriptionFilename = fileNameBase+ReportClient.REPORT_DECSRIPTION_EXTENSION;
242 String basePath = ServiceMain.getInstance().getServerRootDir() +
243 File.separator + JEEServerDeployment.CSPACE_DIR_NAME +
244 File.separator + REPORTS_FOLDER +
245 // File.separator + tenantName +
246 File.separator; // + reportFileName;
248 String compiledFilePath = basePath+compiledReportFilename;
249 File f = new File(compiledFilePath);
250 if(!f.exists()) { // Need to compile the file
251 // First verify that there is a source file.
252 String sourceFilePath = basePath+reportDescriptionFilename;
253 File f2 = new File(sourceFilePath);
254 if(!f2.exists()) { // Missing source file - error!
255 logger.error("Report for csid={} is missing the specified source file: {}",
256 reportCSID, sourceFilePath);
257 throw new RuntimeException("Report is missing the specified source file!");
259 logger.info("Report for csid={} is not compiled. Compiling first, and saving to: {}",
260 reportCSID, compiledFilePath);
261 JasperCompileManager.compileReportToFile(sourceFilePath, compiledFilePath);
264 conn = getConnection();
266 if (logger.isTraceEnabled()) {
267 logger.trace("ReportResource for csid=" + reportCSID
268 +" output as "+outputMimeType+" using report file: "+compiledFilePath);
270 FileInputStream fileStream = new FileInputStream(compiledFilePath);
272 // export report to pdf and build a response with the bytes
273 //JasperExportManager.exportReportToPdf(jasperprint);
275 // Report will be to a byte output array.
276 ByteArrayOutputStream baos = new ByteArrayOutputStream();
278 JRExporter exporter = null;
279 // Strip extension from report filename.
280 String outputFilename = reportFileName;
281 // Strip extension from report filename.
282 int idx = outputFilename.lastIndexOf(".");
284 outputFilename = outputFilename.substring(0, idx);
285 // Strip any sub-dir from report filename.
286 idx = outputFilename.lastIndexOf(File.separator);
288 outputFilename = outputFilename.substring(idx+1);
289 if(outputMimeType.equals(MediaType.APPLICATION_XML)) {
290 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
291 exporter = new JRXmlExporter();
292 outputFilename = outputFilename+".xml";
293 } else if(outputMimeType.equals(MediaType.TEXT_HTML)) {
294 exporter = new JRHtmlExporter();
295 outputFilename = outputFilename+".html";
296 } else if(outputMimeType.equals(ReportClient.PDF_MIME_TYPE)) {
297 exporter = new JRPdfExporter();
298 outputFilename = outputFilename+".pdf";
299 } else if(outputMimeType.equals(ReportClient.CSV_MIME_TYPE)) {
300 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
301 exporter = new JRCsvExporter();
302 exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, ",");
303 outputFilename = outputFilename+".csv";
304 } else if(outputMimeType.equals(ReportClient.TSV_MIME_TYPE)) {
305 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
306 exporter = new JRCsvExporter();
307 exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, "\t");
308 outputFilename = outputFilename+".csv";
309 } else if(outputMimeType.equals(ReportClient.MSWORD_MIME_TYPE) // Understand msword as docx
310 || outputMimeType.equals(ReportClient.OPEN_DOCX_MIME_TYPE)) {
311 exporter = new JRDocxExporter();
312 outputFilename = outputFilename+".docx";
313 } else if(outputMimeType.equals(ReportClient.MSEXCEL_MIME_TYPE) // Understand msexcel as xlsx
314 || outputMimeType.equals(ReportClient.OPEN_XLSX_MIME_TYPE)) {
315 exporter = new JRXlsxExporter();
316 outputFilename = outputFilename+".xlsx";
317 } else if(outputMimeType.equals(ReportClient.MSPPT_MIME_TYPE) // Understand msppt as xlsx
318 || outputMimeType.equals(ReportClient.OPEN_PPTX_MIME_TYPE)) {
319 exporter = new JRPptxExporter();
320 outputFilename = outputFilename+".pptx";
322 logger.error("Reporting: unsupported output MIME type - defaulting to PDF");
323 exporter = new JRPdfExporter();
324 outputFilename = outputFilename+"-default-to.pdf";
326 outReportFileName.append(outputFilename); // Set the out going param to the report's final file name
327 // FIXME: Logging temporarily set to INFO level for CSPACE-5766;
328 // can change to TRACE or DEBUG level as warranted thereafter
329 if (logger.isInfoEnabled()) {
330 logger.info(FileTools.getJavaTmpDirInfo());
333 JasperPrint jasperPrint = JasperFillManager.fillReport(fileStream, params,conn);
335 exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
336 exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
337 exporter.exportReport();
338 result = new ByteArrayInputStream(baos.toByteArray());
341 } catch (SQLException sqle) {
342 // SQLExceptions can be chained. We have at least one exception, so
343 // set up a loop to make sure we let the user know about all of them
344 // if there happens to be more than one.
345 if (logger.isDebugEnabled()) {
346 SQLException tempException = sqle;
347 while (null != tempException) {
348 logger.debug("SQL Exception: " + sqle.getLocalizedMessage());
350 // loop to the next exception
351 tempException = tempException.getNextException();
354 Response response = Response.status(
355 Response.Status.INTERNAL_SERVER_ERROR).entity(
356 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
357 throw new CSWebApplicationException(sqle, response);
358 } catch (JRException jre) {
359 if (logger.isDebugEnabled()) {
360 logger.debug("JR Exception: " + jre.getLocalizedMessage() + " Cause: "+jre.getCause());
362 Response response = Response.status(
363 Response.Status.INTERNAL_SERVER_ERROR).entity(
364 "Invoke failed (Jasper problem) on Report csid=" + reportCSID).type("text/plain").build();
365 throw new CSWebApplicationException(jre, response);
366 } catch (FileNotFoundException fnfe) {
367 if (logger.isDebugEnabled()) {
368 logger.debug("FileNotFoundException: " + fnfe.getLocalizedMessage());
370 Response response = Response.status(
371 Response.Status.INTERNAL_SERVER_ERROR).entity(
372 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
373 throw new CSWebApplicationException(fnfe, response);
378 } catch (SQLException sqle) {
379 // SQLExceptions can be chained. We have at least one exception, so
380 // set up a loop to make sure we let the user know about all of them
381 // if there happens to be more than one.
382 if (logger.isDebugEnabled()) {
383 logger.debug("SQL Exception closing connection: "
384 + sqle.getLocalizedMessage());
386 } catch (Exception e) {
387 if (logger.isDebugEnabled()) {
388 logger.debug("Exception closing connection", e);
395 private Connection getConnection() throws NamingException, SQLException {
396 Connection result = null;
398 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
400 String repositoryName = ctx.getRepositoryName();
401 if (repositoryName != null && repositoryName.trim().isEmpty() == false) {
402 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
403 String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId);
404 result = JDBCTools.getConnection(JDBCTools.NUXEO_READER_DATASOURCE_NAME, databaseName);
406 } catch (Exception e) {
408 throw new NamingException();