]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
867d8d90d80c41f08632ce6da805b3c86f676e3c
[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.File;
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;
36 import java.util.Map;
37 import java.util.regex.Pattern;
38
39 import javax.ws.rs.core.MediaType;
40 import javax.naming.NamingException;
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.JasperFillManager;
49 import net.sf.jasperreports.engine.JasperPrint;
50 import net.sf.jasperreports.engine.design.JasperDesign;
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 import net.sf.jasperreports.engine.xml.JRXmlLoader;
60
61 import org.collectionspace.authentication.AuthN;
62 import org.collectionspace.services.ReportJAXBSchema;
63 import org.collectionspace.services.account.AccountResource;
64 import org.collectionspace.services.authorization.AuthZ;
65 import org.collectionspace.services.authorization.CSpaceResource;
66 import org.collectionspace.services.authorization.PermissionException;
67 import org.collectionspace.services.authorization.URIResourceImpl;
68 import org.collectionspace.services.authorization.perms.ActionType;
69 import org.collectionspace.services.report.ResourceActionGroup;
70 import org.collectionspace.services.report.ResourceActionGroupList;
71 import org.collectionspace.services.report.ReportsCommon.ForRoles;
72 import org.collectionspace.services.report.MIMEType;
73 import org.collectionspace.services.report.MIMETypeItemType;
74 import org.collectionspace.services.report.ReportsCommon;
75 import org.collectionspace.services.report.ReportsOuputMimeList;
76 import org.collectionspace.services.client.PoxPayloadIn;
77 import org.collectionspace.services.client.PoxPayloadOut;
78 import org.collectionspace.services.client.ReportClient;
79 import org.collectionspace.services.common.CSWebApplicationException;
80 import org.collectionspace.services.common.ServiceMain;
81 import org.collectionspace.services.common.api.JEEServerDeployment;
82 import org.collectionspace.services.common.api.FileTools;
83 import org.collectionspace.services.common.api.Tools;
84 import org.collectionspace.services.common.authorization_mgt.ActionGroup;
85 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
86 import org.collectionspace.services.common.context.ServiceBindingUtils;
87 import org.collectionspace.services.common.context.ServiceContext;
88 import org.collectionspace.services.common.document.BadRequestException;
89 import org.collectionspace.services.common.document.DocumentException;
90 import org.collectionspace.services.common.document.DocumentWrapper;
91 import org.collectionspace.services.common.invocable.Invocable;
92 import org.collectionspace.services.common.invocable.InvocationContext;
93 import org.collectionspace.services.common.storage.JDBCTools;
94 import org.collectionspace.services.config.service.ServiceBindingType;
95 import org.collectionspace.services.config.types.PropertyItemType;
96 import org.collectionspace.services.jaxb.InvocableJAXBSchema;
97 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
98 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
99 import org.collectionspace.services.nuxeo.client.java.NuxeoRepositoryClientImpl;
100 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
101
102 import org.jfree.util.Log;
103
104 import org.nuxeo.ecm.core.api.model.PropertyException;
105 import org.nuxeo.ecm.core.api.DocumentModel;
106
107 import org.slf4j.Logger;
108 import org.slf4j.LoggerFactory;
109
110 /**
111  * ReportDocumentModelHandler
112  *
113  * $LastChangedRevision: $
114  * $LastChangedDate: $
115  */
116 public class ReportDocumentModelHandler extends NuxeoDocumentModelHandler<ReportsCommon> {
117                 private final Logger logger = LoggerFactory.getLogger(ReportDocumentModelHandler.class);
118
119                 private static final Pattern INVALID_CSID_PATTERN = Pattern.compile("[^\\w\\-]");
120     private static String REPORTS_FOLDER = "reports";
121     private static String CSID_LIST_SEPARATOR = ",";
122
123     private static String REPORTS_STD_CSID_PARAM = "csid";
124     private static String REPORTS_STD_GROUPCSID_PARAM = "groupcsid";
125     private static String REPORTS_STD_CSIDLIST_PARAM = "csidlist";
126     private static String REPORTS_STD_TENANTID_PARAM = "tenantid";
127
128     //
129     // Map the MIME types from the service bindings to our payload output
130     //
131     public ReportsOuputMimeList getSupportMIMETypes(
132                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
133         //
134         // Create a new payload response instance and initialize it
135         //
136         ReportsOuputMimeList result = new ReportsOuputMimeList();
137         MIMEType resultMIMEType = result.getMIMETypeList();
138         if (resultMIMEType == null) {
139                 result.setMIMETypeList(resultMIMEType = new MIMEType());
140         }
141         List<MIMETypeItemType> resultMIMETypeItemList = resultMIMEType.getMIMEType();
142
143         //
144         // Read the MIME type values from the service bindings and put into our response payload
145         //
146         TenantBindingConfigReaderImpl tReader =
147                 ServiceMain.getInstance().getTenantBindingConfigReader();
148         ServiceBindingType reportServiceBinding = tReader.getServiceBinding(ctx.getTenantId(), ctx.getServiceName());
149         List<PropertyItemType> bindingsMIMETypeList = ServiceBindingUtils.getPropertyValueList(reportServiceBinding, ServiceBindingUtils.OUTPUT_MIME_PROP);
150
151         if (bindingsMIMETypeList != null) {
152                 for (PropertyItemType bindingItemMimeType : bindingsMIMETypeList) {
153                         MIMETypeItemType resultMimeTypeItem = new MIMETypeItemType();
154                         String displayName = bindingItemMimeType.getDisplayName();
155                         if (displayName != null && displayName.trim().isEmpty() == false) {
156                         resultMimeTypeItem.setKey(displayName);
157                         } else {
158                         resultMimeTypeItem.setKey(bindingItemMimeType.getValue());
159                         }
160                         resultMimeTypeItem.setValue(bindingItemMimeType.getValue());
161                         resultMIMETypeItemList.add(resultMimeTypeItem);
162                 }
163         }
164
165         return result;
166     }
167
168     private String getInvocationContextLogging(InvocationContext invContext, Map<String, Object> params) {
169                 String outputMIME = invContext.getOutputMIME();
170                 String mode = invContext.getMode();
171                 String updateCoreValues = invContext.getUpdateCoreValues();
172                 String docType = invContext.getDocType();
173                 String singleCSID = invContext.getSingleCSID();
174                 String groupCSID = invContext.getGroupCSID();
175                 String listCSIDs = invContext.getListCSIDs() == null ? "" : invContext.getListCSIDs().toString();
176
177                 String result =
178                                 "{MIME type: "  + outputMIME +
179                                 "\n \t Context mode: " + mode +
180                                 "\n \t Update Core Values: " + updateCoreValues +
181                                 "\n \t Document type: " + docType +
182                                 "\n \t CSID: " + singleCSID +
183                                 "\n \t Group CSID: " + groupCSID +
184                                 "\n \t List CSIDs: " + listCSIDs +
185                                 "\n \t Parameters: " + params.toString() + "}";
186                 return result;
187         }
188
189         private String assertValidCsid(String csid) throws IllegalArgumentException {
190                 if (INVALID_CSID_PATTERN.matcher(csid).find()) {
191                         throw new IllegalArgumentException("Invalid csid: " + csid);
192                 }
193
194                 return csid;
195         }
196
197         public InputStream invokeReport(
198                         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
199                         String csid,
200                         ReportsCommon reportsCommon,
201                         InvocationContext invContext,
202                         StringBuffer outMimeType,
203                         StringBuffer outReportFileName) throws Exception {
204                 CoreSessionInterface repoSession = null;
205                 boolean releaseRepoSession = false;
206
207                 // Ensure the current user has permission to run this report
208                 if (isAuthoritzed(reportsCommon) == false) {
209                         String msg = String.format("Report Resource: The user '%s' is not authorized to run the report '%s' CSID='%s'",
210                                         AuthN.get().getUserId(), reportsCommon.getName(), csid);
211                         throw new PermissionException(msg);
212                 }
213
214                 String invocationMode = invContext.getMode();
215                 String modeProperty = null;
216                 HashMap<String, Object> params = new HashMap<String, Object>();
217                 params.put(REPORTS_STD_TENANTID_PARAM, ctx.getTenantId());
218                 boolean checkDocType = true;
219
220                 // Note we set before we put in the default ones, so they cannot override tenant or CSID.
221                 setParamsFromContext(params, invContext);
222
223                 if (Invocable.INVOCATION_MODE_SINGLE.equalsIgnoreCase(invocationMode)) {
224                         modeProperty = InvocableJAXBSchema.SUPPORTS_SINGLE_DOC;
225                         params.put(REPORTS_STD_CSID_PARAM, assertValidCsid(invContext.getSingleCSID()));
226                 } else if (Invocable.INVOCATION_MODE_LIST.equalsIgnoreCase(invocationMode)) {
227                         modeProperty = InvocableJAXBSchema.SUPPORTS_DOC_LIST;
228                         List<String> csids = null;
229                         InvocationContext.ListCSIDs listThing = invContext.getListCSIDs();
230                                 if (listThing!=null) {
231                                         csids = listThing.getCsid();
232                                 }
233                                 if (csids==null||csids.isEmpty()){
234                                 throw new BadRequestException(
235                                                 "ReportResource: Report invoked in list mode, with no csids in list." );
236                                 }
237                                 StringBuilder sb = new StringBuilder();
238                                 boolean first = true;
239                                 for(String csidItem : csids) {
240                                         if(first)
241                                                 first = false;
242                                         else
243                                                 sb.append(CSID_LIST_SEPARATOR);
244                                         sb.append(assertValidCsid(csidItem));
245                                 }
246                 params.put(REPORTS_STD_CSIDLIST_PARAM, sb.toString());
247                 } else if(Invocable.INVOCATION_MODE_GROUP.equalsIgnoreCase(invocationMode)) {
248                         modeProperty = InvocableJAXBSchema.SUPPORTS_GROUP;
249                         params.put(REPORTS_STD_GROUPCSID_PARAM, assertValidCsid(invContext.getGroupCSID()));
250                 } else if(Invocable.INVOCATION_MODE_NO_CONTEXT.equalsIgnoreCase(invocationMode)) {
251                         modeProperty = InvocableJAXBSchema.SUPPORTS_NO_CONTEXT;
252                         checkDocType = false;
253                 } else {
254                         throw new BadRequestException("ReportResource: unknown Invocation Mode: "
255                                 +invocationMode);
256                 }
257
258                 logger.debug("The invocation context is: \n " + getInvocationContextLogging(invContext, params));
259                 logger.debug("The report is being called with the following parameters, which are being passed to Jasper: \n" + params.toString());
260                 logger.debug("The mode being passed to Jasper is: " + invocationMode);
261
262                 NuxeoRepositoryClientImpl repoClient = (NuxeoRepositoryClientImpl)this.getRepositoryClient(ctx);
263                 repoSession = this.getRepositorySession();
264                 if (repoSession == null) {
265                         repoSession = repoClient.getRepositorySession(ctx);
266                         releaseRepoSession = true;
267                 }
268
269                 // Get properties from the report docModel, and release the session
270                 String reportFileNameProperty;
271                 try {
272                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, csid);
273                         DocumentModel docModel = wrapper.getWrappedObject();
274                         Boolean supports = (Boolean) NuxeoUtils.getProperyValue(docModel, modeProperty); //docModel.getPropertyValue(modeProperty);
275                         if(supports == null || !supports) {
276                                 throw new BadRequestException(
277                                                 "ReportResource: This Report does not support Invocation Mode: "
278                                         +invocationMode);
279                         }
280                 if (checkDocType) {
281                         List<String> forDocTypeList =
282                                 (List<String>) NuxeoUtils.getProperyValue(docModel, InvocableJAXBSchema.FOR_DOC_TYPES); //docModel.getPropertyValue(InvocableJAXBSchema.FOR_DOC_TYPES);
283                         if (forDocTypeList==null || !forDocTypeList.contains(invContext.getDocType())) {
284                                 throw new BadRequestException(
285                                                 "ReportResource: Invoked with unsupported document type: "
286                                                 +invContext.getDocType());
287                         }
288                 }
289                 reportFileNameProperty = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.FILENAME); //docModel.getPropertyValue(ReportJAXBSchema.FILENAME)); // Set the outgoing param with the report file name
290                         //
291                 // 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,
292                 // use the default MIME type.
293                 //
294                 if (!Tools.isEmpty(invContext.getOutputMIME())) {
295                         outMimeType.append(invContext.getOutputMIME());
296                 } else if (Tools.isEmpty(outMimeType.toString()) && params.containsKey("OutputMIME")) {
297                         // See UCB - https://github.com/cspace-deployment/services/pull/140/files
298                         outMimeType.append(params.get("OutputMIME"));
299                 } else {
300                         // Use the default
301                         String reportOutputMime = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.OUTPUT_MIME); //docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
302                         if (!Tools.isEmpty(reportOutputMime)) {
303                                 outMimeType.append(reportOutputMime);
304                         } else {
305                                 outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
306                         }
307                 }
308                 } catch (PropertyException pe) {
309                         if (logger.isDebugEnabled()) {
310                                 logger.debug("Property exception getting report values: ", pe);
311                         }
312                         throw pe;
313                 } catch (DocumentException de) {
314                         if (logger.isDebugEnabled()) {
315                                 logger.debug("Problem getting report report: ", de);
316                         }
317                         throw de;
318                 } catch (Exception e) {
319                         if (logger.isDebugEnabled()) {
320                                 logger.debug("Caught exception ", e);
321                         }
322                         throw new DocumentException(e);
323                 } finally {
324                         if (releaseRepoSession && repoSession != null) {
325                                 repoClient.releaseRepositorySession(ctx, repoSession);
326                         }
327                 }
328
329         return buildReportResult(csid, params, reportFileNameProperty, outMimeType.toString(), outReportFileName);
330         }
331
332         private void setParamsFromContext(Map<String, Object> params, InvocationContext invContext) {
333                 InvocationContext.Params icParams = invContext.getParams();
334                 if(icParams!= null) {
335                         List<InvocationContext.Params.Param> icParamList = icParams.getParam();
336                         if(icParamList != null) {
337                                 for(InvocationContext.Params.Param param:icParamList) {
338                                         String key = param.getKey();
339                                         String value = param.getValue();
340                                         if(!Tools.isEmpty(key) && !Tools.isEmpty(value)) {
341                                                 params.put(key, value);
342                                         }
343                                 }
344                         }
345                 }
346
347         }
348
349     private InputStream buildReportResult(String reportCSID,
350                 HashMap<String, Object> params, String reportFileName, String outputMimeType, StringBuffer outReportFileName)
351                                 throws Exception {
352                 Connection conn = null;
353                 InputStream result = null;
354
355         try {
356                 String fileNameBase = Tools.getFilenameBase(reportFileName);
357                 String compiledReportFilename = fileNameBase+ReportClient.COMPILED_REPORT_EXTENSION;
358                 String reportDescriptionFilename = fileNameBase+ReportClient.REPORT_DECSRIPTION_EXTENSION;
359
360                         String basePath = ServiceMain.getInstance().getServerRootDir() +
361                                                                 File.separator + JEEServerDeployment.CSPACE_DIR_NAME +
362                                                                 File.separator + REPORTS_FOLDER +
363                                                                 // File.separator + tenantName +
364                                                                 File.separator; // + reportFileName;
365
366                         String compiledFilePath = basePath+compiledReportFilename;
367                         File f = new File(compiledFilePath);
368                         if(!f.exists()) { // Need to compile the file
369                                 // First verify that there is a source file.
370                                 String sourceFilePath = basePath+reportDescriptionFilename;
371                                 File f2 = new File(sourceFilePath);
372                                 if(!f2.exists()) { // Missing source file - error!
373                                         logger.error("Report for csid={} is missing the specified source file: {}",
374                                                                         reportCSID, sourceFilePath);
375                                         throw new RuntimeException("Report is missing the specified source file!");
376                                 }
377
378                                 logger.info("Report for csid={} is not compiled. Compiling first, and saving to: {}",
379                                         reportCSID, compiledFilePath);
380
381                                 JasperDesign design = JRXmlLoader.load(sourceFilePath);
382
383                                 design.setScriptletClass("org.collectionspace.services.report.jasperreports.CSpaceReportScriptlet");
384
385                                 JasperCompileManager.compileReportToFile(design, compiledFilePath);
386                         }
387
388                         conn = getConnection();
389
390             if (logger.isTraceEnabled()) {
391                 logger.trace("ReportResource for csid=" + reportCSID
392                                 +" output as "+outputMimeType+" using report file: "+compiledFilePath);
393             }
394                         FileInputStream fileStream = new FileInputStream(compiledFilePath);
395
396                         // export report to pdf and build a response with the bytes
397                         //JasperExportManager.exportReportToPdf(jasperprint);
398
399                         JRExporter exporter = null;
400                         // Strip extension from report filename.
401                         String outputFilename = reportFileName;
402                         // Strip extension from report filename.
403                         int idx = outputFilename.lastIndexOf(".");
404                         if(idx>0)
405                                 outputFilename = outputFilename.substring(0, idx);
406                         // Strip any sub-dir from report filename.
407                         idx = outputFilename.lastIndexOf(File.separator);
408                         if(idx>0)
409                                 outputFilename = outputFilename.substring(idx+1);
410                         if(outputMimeType.equals(MediaType.APPLICATION_XML)) {
411                                 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
412                                 exporter = new JRXmlExporter();
413                                 outputFilename = outputFilename+".xml";
414                         } else if(outputMimeType.equals(MediaType.TEXT_HTML)) {
415                                 exporter = new JRHtmlExporter();
416                                 outputFilename = outputFilename+".html";
417                         } else if(outputMimeType.equals(ReportClient.PDF_MIME_TYPE)) {
418                                 exporter = new JRPdfExporter();
419                                 outputFilename = outputFilename+".pdf";
420                         } else if(outputMimeType.equals(ReportClient.CSV_MIME_TYPE)) {
421                                 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
422                                 exporter = new JRCsvExporter();
423                                 exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, ",");
424                                 outputFilename = outputFilename+".csv";
425                         } else if(outputMimeType.equals(ReportClient.TSV_MIME_TYPE)) {
426                                 params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
427                                 exporter = new JRCsvExporter();
428                                 exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, "\t");
429                                 outputFilename = outputFilename+".csv";
430                         } else if(outputMimeType.equals(ReportClient.MSWORD_MIME_TYPE)  // Understand msword as docx
431                                         || outputMimeType.equals(ReportClient.OPEN_DOCX_MIME_TYPE)) {
432                                 exporter = new JRDocxExporter();
433                                 outputFilename = outputFilename+".docx";
434                         } else if(outputMimeType.equals(ReportClient.MSEXCEL_MIME_TYPE) // Understand msexcel as xlsx
435                                         || outputMimeType.equals(ReportClient.OPEN_XLSX_MIME_TYPE)) {
436                                 exporter = new JRXlsxExporter();
437                                 outputFilename = outputFilename+".xlsx";
438                         } else if(outputMimeType.equals(ReportClient.MSPPT_MIME_TYPE)   // Understand msppt as xlsx
439                                         || outputMimeType.equals(ReportClient.OPEN_PPTX_MIME_TYPE)) {
440                                 exporter = new JRPptxExporter();
441                                 outputFilename = outputFilename+".pptx";
442                         } else {
443                                 logger.error("Reporting: unsupported output MIME type - defaulting to PDF");
444                                 exporter = new JRPdfExporter();
445                                 outputFilename = outputFilename+"-default-to.pdf";
446                         }
447                         outReportFileName.append(outputFilename); // Set the out going param to the report's final file name
448                         // FIXME: Logging temporarily set to INFO level for CSPACE-5766;
449                         // can change to TRACE or DEBUG level as warranted thereafter
450                         if (logger.isInfoEnabled()) {
451                             logger.info(FileTools.getJavaTmpDirInfo());
452                         }
453                         // fill the report
454                         JasperPrint jasperPrint = JasperFillManager.fillReport(fileStream, params,conn);
455
456                         // Report will be to a temporary file.
457                         File tempOutputFile = Files.createTempFile("report-", null).toFile();
458                         FileOutputStream tempOutputStream = new FileOutputStream(tempOutputFile);
459                         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
460                         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, tempOutputStream);
461                         exporter.exportReport();
462                         tempOutputStream.close();
463
464                         result = new FileInputStream(tempOutputFile);
465                 return result;
466         } catch (SQLException sqle) {
467             // SQLExceptions can be chained. We have at least one exception, so
468             // set up a loop to make sure we let the user know about all of them
469             // if there happens to be more than one.
470             if (logger.isDebugEnabled()) {
471                     SQLException tempException = sqle;
472                     while (null != tempException) {
473                                 logger.debug("SQL Exception: " + sqle.getLocalizedMessage());
474
475                         // loop to the next exception
476                         tempException = tempException.getNextException();
477                     }
478             }
479             Response response = Response.status(
480                     Response.Status.INTERNAL_SERVER_ERROR).entity(
481                                 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
482             throw new CSWebApplicationException(sqle, response);
483         } catch (JRException jre) {
484             if (logger.isDebugEnabled()) {
485                 logger.debug("JR Exception: " + jre.getLocalizedMessage() + " Cause: "+jre.getCause());
486             }
487             Response response = Response.status(
488                     Response.Status.INTERNAL_SERVER_ERROR).entity(
489                                 "Invoke failed (Jasper problem) on Report csid=" + reportCSID).type("text/plain").build();
490             throw new CSWebApplicationException(jre, response);
491         } catch (FileNotFoundException fnfe) {
492             if (logger.isDebugEnabled()) {
493                 logger.debug("FileNotFoundException: " + fnfe.getLocalizedMessage());
494             }
495             Response response = Response.status(
496                     Response.Status.INTERNAL_SERVER_ERROR).entity(
497                                 "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
498             throw new CSWebApplicationException(fnfe, response);
499                 } finally {
500                 if (conn!=null) {
501                         try {
502                                 conn.close();
503                 } catch (SQLException sqle) {
504                     // SQLExceptions can be chained. We have at least one exception, so
505                     // set up a loop to make sure we let the user know about all of them
506                     // if there happens to be more than one.
507                     if (logger.isDebugEnabled()) {
508                                 logger.debug("SQL Exception closing connection: "
509                                                 + sqle.getLocalizedMessage());
510                     }
511                 } catch (Exception e) {
512                     if (logger.isDebugEnabled()) {
513                         logger.debug("Exception closing connection", e);
514                     }
515                 }
516                 }
517         }
518     }
519
520     private Connection getConnection() throws NamingException, SQLException {
521         Connection result = null;
522
523         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
524         try {
525                 String repositoryName = ctx.getRepositoryName();
526                 if (repositoryName != null && repositoryName.trim().isEmpty() == false) {
527                         String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
528                         String databaseName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId);
529                         result = JDBCTools.getConnection(JDBCTools.NUXEO_READER_DATASOURCE_NAME, databaseName);
530                 }
531                 } catch (Exception e) {
532                         Log.error(e);
533                         throw new NamingException();
534                 }
535
536         return result;
537     }
538
539         /**
540          * Check to see if the current user is authorized to run/invoke this report.  If the report
541          * did not specify any permissions, we assume that the current user is authorized to run the report.
542          * @param reportsCommon
543          * @return
544          */
545         protected boolean isAuthoritzedWithPermissions(ReportsCommon reportsCommon) {
546                 boolean result = true;
547
548                 ResourceActionGroupList resourceActionGroupList = reportsCommon.getResourceActionGroupList();
549                 if (resourceActionGroupList != null) {
550                         String tenantId = AuthN.get().getCurrentTenantId();
551                         for (ResourceActionGroup resourceActionGroup: resourceActionGroupList.getResourceActionGroup()) {
552                                 String resourceName = resourceActionGroup.getResourceName();
553                                 ActionGroup actionGroup = ActionGroup.creatActionGroup(resourceActionGroup.getActionGroup());
554                                 for (ActionType actionType: actionGroup.getActions()) {
555                                         CSpaceResource res = new URIResourceImpl(tenantId, resourceName, AuthZ.getMethod(actionType));
556                                         if (AuthZ.get().isAccessAllowed(res) == false) {
557                                                 return false;
558                                         }
559                                 }
560                         }
561                 }
562
563                 return result;
564         }
565
566         /**
567          * Returns true if we found any required permissions.
568          *
569          * @param reportCommon
570          * @return
571          */
572         private boolean hasRequiredPermissions(ReportsCommon reportCommon) {
573                 boolean result = false;
574
575                 try {
576                         result = reportCommon.getResourceActionGroupList().getResourceActionGroup().size() > 0;
577                 } catch (NullPointerException e) {
578                         // ignore exception, we're just testing to see if we have any list elements
579                 }
580
581                 return result;
582         }
583
584         /**
585          * Returns true if we found any required roles.
586          *
587          * @param reportCommon
588          * @return
589          */
590         private boolean hasRequiredRoles(ReportsCommon reportCommon) {
591                 boolean result = false;
592
593                 try {
594                         result = reportCommon.getForRoles().getRoleDisplayName().size() > 0;
595                 } catch (NullPointerException e) {
596                         // ignore exception, we're just testing to see if we have any list elements
597                 }
598
599                 return result;
600         }
601
602         /**
603          * The current user is authorized to run the report if:
604          *      1. No permissions or roles are specified in the report
605          *  2. No roles are specified, but permissions are specified and the current user has those permissions
606          *  3. Roles are specified and the current user is a member of at least one of the roles.
607          *
608          * @param reportsCommon
609          * @return
610          */
611         protected boolean isAuthoritzed(ReportsCommon reportsCommon) {
612                 boolean result = true;
613
614                 if (hasRequiredRoles(reportsCommon)) {
615                         result = isAuthorizedWithRoles(reportsCommon);
616                 } else if (hasRequiredPermissions(reportsCommon)) {
617                         result = isAuthoritzedWithPermissions(reportsCommon);
618                 }
619
620                 return result;
621         }
622
623         protected boolean isAuthorizedWithRoles(ReportsCommon reportCommon) {
624                 boolean result = false;
625
626                 ForRoles forRolesList = reportCommon.getForRoles();
627                 if (forRolesList != null) {
628                         AccountResource accountResource = new AccountResource();
629                         List<String> roleDisplayNameList = accountResource.getAccountRoleDisplayNames(AuthN.get().getUserId(), AuthN.get().getCurrentTenantId());
630                         for (String target : forRolesList.getRoleDisplayName()) {
631                                 if (Tools.listContainsIgnoreCase(roleDisplayNameList, target)) {
632                                         result = true;
633                                         break;
634                                 }
635                         }
636                 }
637
638                 return result;
639         }
640
641 }