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