2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.report.nuxeo;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.InputStream;
31 import java.nio.file.Files;
32 import java.sql.Connection;
33 import java.sql.SQLException;
34 import java.util.HashMap;
35 import java.util.List;
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;
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;
106 * ReportDocumentModelHandler
108 * $LastChangedRevision: $
109 * $LastChangedDate: $
111 public class ReportDocumentModelHandler extends NuxeoDocumentModelHandler<ReportsCommon> {
112 private final Logger logger = LoggerFactory.getLogger(ReportDocumentModelHandler.class);
114 private static final Pattern INVALID_CSID_PATTERN = Pattern.compile("[^\\w\\-]");
115 private static String CSID_LIST_SEPARATOR = ",";
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";
123 // Map the MIME types from the service bindings to our payload output
125 public ReportsOuputMimeList getSupportMIMETypes(
126 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
128 // Create a new payload response instance and initialize it
130 ReportsOuputMimeList result = new ReportsOuputMimeList();
131 MIMEType resultMIMEType = result.getMIMETypeList();
132 if (resultMIMEType == null) {
133 result.setMIMETypeList(resultMIMEType = new MIMEType());
135 List<MIMETypeItemType> resultMIMETypeItemList = resultMIMEType.getMIMEType();
138 // Read the MIME type values from the service bindings and put into our response payload
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);
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);
152 resultMimeTypeItem.setKey(bindingItemMimeType.getValue());
154 resultMimeTypeItem.setValue(bindingItemMimeType.getValue());
155 resultMIMETypeItemList.add(resultMimeTypeItem);
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();
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() + "}";
183 private String assertValidCsid(String csid) throws IllegalArgumentException {
184 if (INVALID_CSID_PATTERN.matcher(csid).find()) {
185 throw new IllegalArgumentException("Invalid csid: " + csid);
191 public InputStream invokeReport(
192 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
194 ReportsCommon reportsCommon,
195 InvocationContext invContext,
196 StringBuffer outMimeType,
197 StringBuffer outReportFileName) throws Exception {
198 CoreSessionInterface repoSession = null;
199 boolean releaseRepoSession = false;
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);
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;
214 // Note we set before we put in the default ones, so they cannot override tenant or CSID.
215 setParamsFromContext(params, invContext);
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();
227 if (csids==null||csids.isEmpty()){
228 throw new BadRequestException(
229 "ReportResource: Report invoked in list mode, with no csids in list." );
231 StringBuilder sb = new StringBuilder();
232 boolean first = true;
233 for (String csidItem : csids) {
237 sb.append(CSID_LIST_SEPARATOR);
239 sb.append(assertValidCsid(csidItem));
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;
249 throw new BadRequestException("ReportResource: unknown Invocation Mode: "
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);
257 NuxeoRepositoryClientImpl repoClient = (NuxeoRepositoryClientImpl)this.getRepositoryClient(ctx);
258 repoSession = this.getRepositorySession();
259 if (repoSession == null) {
260 repoSession = repoClient.getRepositorySession(ctx);
261 releaseRepoSession = true;
264 // Get properties from the report docModel, and release the session
265 String reportFileNameProperty;
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: "
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());
284 reportFileNameProperty = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.FILENAME); //docModel.getPropertyValue(ReportJAXBSchema.FILENAME)); // Set the outgoing param with the report file name
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.
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"));
296 String reportOutputMime = (String) NuxeoUtils.getProperyValue(docModel, ReportJAXBSchema.OUTPUT_MIME); //docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
297 if (!Tools.isEmpty(reportOutputMime)) {
298 outMimeType.append(reportOutputMime);
300 outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
303 } catch (PropertyException pe) {
304 if (logger.isDebugEnabled()) {
305 logger.debug("Property exception getting report values: ", pe);
308 } catch (DocumentException de) {
309 if (logger.isDebugEnabled()) {
310 logger.debug("Problem getting report report: ", de);
313 } catch (Exception e) {
314 if (logger.isDebugEnabled()) {
315 logger.debug("Caught exception ", e);
317 throw new DocumentException(e);
319 if (releaseRepoSession && repoSession != null) {
320 repoClient.releaseRepositorySession(ctx, repoSession);
324 return buildReportResult(csid, params, reportFileNameProperty, outMimeType.toString(), outReportFileName);
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);
344 private InputStream buildReportResult(
346 HashMap<String, Object> params,
347 String reportFileName,
348 String outputMimeType,
349 StringBuffer outReportFileName
352 Connection conn = null;
353 InputStream result = null;
356 String reportName = Tools.getFilenameBase(reportFileName);
357 File reportCompiledFile = ReportResource.getReportCompiledFile(reportName);
359 if (!reportCompiledFile.exists()) {
360 // Need to compile the file.
362 File reportSourceFile = ReportResource.getReportSourceFile(reportName);
364 if(!reportSourceFile.exists()) {
365 logger.error("Report for csid={} is missing source file: {}",
366 reportCSID, reportSourceFile.getAbsolutePath());
368 throw new RuntimeException("Report is missing source file");
371 logger.info("Report for csid={} is not compiled. Compiling first, and saving to: {}",
372 reportCSID, reportCompiledFile.getAbsolutePath());
374 JasperDesign design = JRXmlLoader.load(reportSourceFile.getAbsolutePath());
376 design.setScriptletClass("org.collectionspace.services.report.jasperreports.CSpaceReportScriptlet");
378 JasperCompileManager.compileReportToFile(design, reportCompiledFile.getAbsolutePath());
381 conn = getConnection();
383 if (logger.isTraceEnabled()) {
384 logger.trace("ReportResource for csid=" + reportCSID
385 + " output as " + outputMimeType + " using report file: " + reportCompiledFile.getAbsolutePath());
388 FileInputStream fileStream = new FileInputStream(reportCompiledFile);
390 // export report to pdf and build a response with the bytes
391 //JasperExportManager.exportReportToPdf(jasperprint);
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(".");
399 outputFilename = outputFilename.substring(0, idx);
401 // Strip any sub-dir from report filename.
402 idx = outputFilename.lastIndexOf(File.separator);
404 outputFilename = outputFilename.substring(idx + 1);
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";
439 logger.error("Reporting: unsupported output MIME type - defaulting to PDF");
440 exporter = new JRPdfExporter();
441 outputFilename = outputFilename+"-default-to.pdf";
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());
450 JasperPrint jasperPrint = JasperFillManager.fillReport(fileStream, params,conn);
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();
460 result = new FileInputStream(tempOutputFile);
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());
471 // loop to the next exception
472 tempException = tempException.getNextException();
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());
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());
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);
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());
507 } catch (Exception e) {
508 if (logger.isDebugEnabled()) {
509 logger.debug("Exception closing connection", e);
516 private Connection getConnection() throws NamingException, SQLException {
517 Connection result = null;
519 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
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);
527 } catch (Exception e) {
529 throw new NamingException();
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
541 protected boolean isAuthoritzedWithPermissions(ReportsCommon reportsCommon) {
542 boolean result = true;
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) {
563 * Returns true if we found any required permissions.
565 * @param reportCommon
568 private boolean hasRequiredPermissions(ReportsCommon reportCommon) {
569 boolean result = false;
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
581 * Returns true if we found any required roles.
583 * @param reportCommon
586 private boolean hasRequiredRoles(ReportsCommon reportCommon) {
587 boolean result = false;
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
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.
604 * @param reportsCommon
607 protected boolean isAuthoritzed(ReportsCommon reportsCommon) {
608 boolean result = true;
610 if (hasRequiredRoles(reportsCommon)) {
611 result = isAuthorizedWithRoles(reportsCommon);
612 } else if (hasRequiredPermissions(reportsCommon)) {
613 result = isAuthoritzedWithPermissions(reportsCommon);
619 protected boolean isAuthorizedWithRoles(ReportsCommon reportCommon) {
620 boolean result = false;
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)) {