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