MIFOSX-195: some formatting and clean up whilst testing this issue.

This commit is contained in:
Keith Woodlock
2013-05-07 10:18:54 +01:00
parent d8913ab758
commit e8b8cf4f8a
7 changed files with 434 additions and 562 deletions
@@ -5,8 +5,8 @@
*/ */
package org.mifosplatform.infrastructure.core.service; package org.mifosplatform.infrastructure.core.service;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource; import javax.sql.DataSource;
@@ -28,7 +28,7 @@ import org.springframework.stereotype.Service;
@Service @Service
public class TomcatJdbcDataSourcePerTenantService implements DataSourcePerTenantService { public class TomcatJdbcDataSourcePerTenantService implements DataSourcePerTenantService {
private final Map<Long, DataSource> tenantToDataSourceMap = new ConcurrentHashMap<Long, DataSource>(1); private final Map<Long, DataSource> tenantToDataSourceMap = new HashMap<Long, DataSource>(1);
private final DataSource tenantDataSource; private final DataSource tenantDataSource;
@Autowired @Autowired
@@ -44,9 +44,9 @@ public class TomcatJdbcDataSourcePerTenantService implements DataSourcePerTenant
MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); MifosPlatformTenant tenant = ThreadLocalContextUtil.getTenant();
if (tenant != null) { if (tenant != null) {
synchronized(this.tenantToDataSourceMap) synchronized (this.tenantToDataSourceMap) {
{ // if tenant information available switch to appropriate
// if tenant information available switch to appropriate datasource // datasource
// for that tenant. // for that tenant.
if (this.tenantToDataSourceMap.containsKey(tenant.getId())) { if (this.tenantToDataSourceMap.containsKey(tenant.getId())) {
tenantDataSource = this.tenantToDataSourceMap.get(tenant.getId()); tenantDataSource = this.tenantToDataSourceMap.get(tenant.getId());
@@ -6,7 +6,6 @@
package org.mifosplatform.infrastructure.dataqueries.domain; package org.mifosplatform.infrastructure.dataqueries.domain;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@@ -34,7 +33,7 @@ import com.google.gson.JsonArray;
@Entity @Entity
@Table(name = "stretchy_report", uniqueConstraints = { @UniqueConstraint(columnNames = { "report_name" }, name = "unq_report_name") }) @Table(name = "stretchy_report", uniqueConstraints = { @UniqueConstraint(columnNames = { "report_name" }, name = "unq_report_name") })
public class Report extends AbstractPersistable<Long> { public final class Report extends AbstractPersistable<Long> {
@Column(name = "report_name", nullable = false, unique = true) @Column(name = "report_name", nullable = false, unique = true)
private String reportName; private String reportName;
@@ -63,7 +62,7 @@ public class Report extends AbstractPersistable<Long> {
@LazyCollection(LazyCollectionOption.FALSE) @LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "report", orphanRemoval = true) @OneToMany(cascade = CascadeType.ALL, mappedBy = "report", orphanRemoval = true)
private Set<ReportParameterUsage> reportParameterUsages = new HashSet<ReportParameterUsage>(); private final Set<ReportParameterUsage> reportParameterUsages = new HashSet<ReportParameterUsage>();
public static Report fromJson(final JsonCommand command) { public static Report fromJson(final JsonCommand command) {
@@ -75,36 +74,23 @@ public class Report extends AbstractPersistable<Long> {
boolean useReport = false; boolean useReport = false;
String reportSql = null; String reportSql = null;
if (command.parameterExists("reportName")) if (command.parameterExists("reportName")) reportName = command.stringValueOfParameterNamed("reportName");
reportName = command.stringValueOfParameterNamed("reportName"); if (command.parameterExists("reportType")) reportType = command.stringValueOfParameterNamed("reportType");
if (command.parameterExists("reportType")) if (command.parameterExists("reportSubType")) reportSubType = command.stringValueOfParameterNamed("reportSubType");
reportType = command.stringValueOfParameterNamed("reportType"); if (command.parameterExists("reportCategory")) reportCategory = command.stringValueOfParameterNamed("reportCategory");
if (command.parameterExists("reportSubType")) if (command.parameterExists("description")) description = command.stringValueOfParameterNamed("description");
reportSubType = command if (command.parameterExists("useReport")) useReport = command.booleanPrimitiveValueOfParameterNamed("useReport");
.stringValueOfParameterNamed("reportSubType"); if (command.parameterExists("reportSql")) reportSql = command.stringValueOfParameterNamed("reportSql");
if (command.parameterExists("reportCategory"))
reportCategory = command
.stringValueOfParameterNamed("reportCategory");
if (command.parameterExists("description"))
description = command.stringValueOfParameterNamed("description");
if (command.parameterExists("useReport"))
useReport = command
.booleanPrimitiveValueOfParameterNamed("useReport");
if (command.parameterExists("reportSql"))
reportSql = command.stringValueOfParameterNamed("reportSql");
return new Report(reportName, reportType, reportSubType, return new Report(reportName, reportType, reportSubType, reportCategory, description, useReport, reportSql);
reportCategory, description, useReport, reportSql);
} }
protected Report() { protected Report() {
// //
} }
public Report(final String reportName, final String reportType, public Report(final String reportName, final String reportType, final String reportSubType, final String reportCategory,
final String reportSubType, final String reportCategory, final String description, final boolean useReport, final String reportSql) {
final String description, final boolean useReport,
final String reportSql) {
this.reportName = reportName; this.reportName = reportName;
this.reportType = reportType; this.reportType = reportType;
this.reportSubType = reportSubType; this.reportSubType = reportSubType;
@@ -118,68 +104,56 @@ public class Report extends AbstractPersistable<Long> {
public Map<String, Object> update(final JsonCommand command) { public Map<String, Object> update(final JsonCommand command) {
final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>( final Map<String, Object> actualChanges = new LinkedHashMap<String, Object>(8);
8);
String paramName = "reportName"; String paramName = "reportName";
if (command.isChangeInStringParameterNamed(paramName, this.reportName)) { if (command.isChangeInStringParameterNamed(paramName, this.reportName)) {
final String newValue = command final String newValue = command.stringValueOfParameterNamed(paramName);
.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.reportName = StringUtils.defaultIfEmpty(newValue, null); this.reportName = StringUtils.defaultIfEmpty(newValue, null);
} }
paramName = "reportType"; paramName = "reportType";
if (command.isChangeInStringParameterNamed(paramName, this.reportType)) { if (command.isChangeInStringParameterNamed(paramName, this.reportType)) {
final String newValue = command final String newValue = command.stringValueOfParameterNamed(paramName);
.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.reportType = StringUtils.defaultIfEmpty(newValue, null); this.reportType = StringUtils.defaultIfEmpty(newValue, null);
} }
paramName = "reportSubType"; paramName = "reportSubType";
if (command.isChangeInStringParameterNamed(paramName, if (command.isChangeInStringParameterNamed(paramName, this.reportSubType)) {
this.reportSubType)) { final String newValue = command.stringValueOfParameterNamed(paramName);
final String newValue = command
.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.reportSubType = StringUtils.defaultIfEmpty(newValue, null); this.reportSubType = StringUtils.defaultIfEmpty(newValue, null);
} }
paramName = "reportCategory"; paramName = "reportCategory";
if (command.isChangeInStringParameterNamed(paramName, if (command.isChangeInStringParameterNamed(paramName, this.reportCategory)) {
this.reportCategory)) { final String newValue = command.stringValueOfParameterNamed(paramName);
final String newValue = command
.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.reportCategory = StringUtils.defaultIfEmpty(newValue, null); this.reportCategory = StringUtils.defaultIfEmpty(newValue, null);
} }
paramName = "description"; paramName = "description";
if (command.isChangeInStringParameterNamed(paramName, this.description)) { if (command.isChangeInStringParameterNamed(paramName, this.description)) {
final String newValue = command final String newValue = command.stringValueOfParameterNamed(paramName);
.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.description = StringUtils.defaultIfEmpty(newValue, null); this.description = StringUtils.defaultIfEmpty(newValue, null);
} }
paramName = "useReport"; paramName = "useReport";
if (command.isChangeInBooleanParameterNamed(paramName, this.useReport)) { if (command.isChangeInBooleanParameterNamed(paramName, this.useReport)) {
final boolean newValue = command final boolean newValue = command.booleanPrimitiveValueOfParameterNamed(paramName);
.booleanPrimitiveValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.useReport = newValue; this.useReport = newValue;
} }
paramName = "reportSql"; paramName = "reportSql";
if (command.isChangeInStringParameterNamed(paramName, this.reportSql)) { if (command.isChangeInStringParameterNamed(paramName, this.reportSql)) {
final String newValue = command final String newValue = command.stringValueOfParameterNamed(paramName);
.stringValueOfParameterNamed(paramName);
actualChanges.put(paramName, newValue); actualChanges.put(paramName, newValue);
this.reportSql = StringUtils.defaultIfEmpty(newValue, null); this.reportSql = StringUtils.defaultIfEmpty(newValue, null);
} }
final String reportParametersParamName = "reportParameters"; final String reportParametersParamName = "reportParameters";
if (command.hasParameter(reportParametersParamName)) { if (command.hasParameter(reportParametersParamName)) {
JsonArray jsonArray = command JsonArray jsonArray = command.arrayOfParameterNamed(reportParametersParamName);
.arrayOfParameterNamed(reportParametersParamName);
if (jsonArray != null) { if (jsonArray != null) {
actualChanges.put(reportParametersParamName, actualChanges.put(reportParametersParamName, command.jsonFragment(reportParametersParamName));
command.jsonFragment(reportParametersParamName));
} }
} }
@@ -188,12 +162,9 @@ public class Report extends AbstractPersistable<Long> {
if (!actualChanges.isEmpty()) { if (!actualChanges.isEmpty()) {
if (isCoreReport()) { if (isCoreReport()) {
for (final String key : actualChanges.keySet()) { for (final String key : actualChanges.keySet()) {
if (!(key.equals("useReport"))) { if (!(key.equals("useReport"))) { throw new PlatformDataIntegrityException(
throw new PlatformDataIntegrityException(
"error.msg.only.use.report.can.be.updated.for.core.report", "error.msg.only.use.report.can.be.updated.for.core.report",
"Only the Use Report field can be updated for Core Reports", "Only the Use Report field can be updated for Core Reports", key); }
key);
}
} }
} }
} }
@@ -205,95 +176,64 @@ public class Report extends AbstractPersistable<Long> {
return coreReport; return coreReport;
} }
public ReportParameterUsage findReportParameterById(final Long reportParameterId) {
ReportParameterUsage reportParameterUsage = null;
for (ReportParameterUsage rpu : this.reportParameterUsages) {
if (rpu.hasIdOf(reportParameterId)) {
reportParameterUsage = rpu;
break;
}
}
return reportParameterUsage;
}
private void validate() { private void validate() {
final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder( final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors).resource("report");
dataValidationErrors).resource("report");
baseDataValidator.reset().parameter("reportName") baseDataValidator.reset().parameter("reportName").value(this.reportName).notBlank().notExceedingLengthOf(100);
.value(this.reportName).notBlank().notExceedingLengthOf(100);
baseDataValidator baseDataValidator.reset().parameter("reportType").value(this.reportType).notBlank()
.reset() .isOneOfTheseValues(new Object[] { "Table", "Pentaho", "Chart" });
.parameter("reportType")
.value(this.reportType)
.notBlank()
.isOneOfTheseValues(
new Object[] { "Table", "Pentaho", "Chart" });
baseDataValidator.reset().parameter("reportSubType") baseDataValidator.reset().parameter("reportSubType").value(this.reportSubType).notExceedingLengthOf(20);
.value(this.reportSubType).notExceedingLengthOf(20);
if (StringUtils.isNotBlank(this.reportType)) { if (StringUtils.isNotBlank(this.reportType)) {
if (this.reportType.equals("Chart")) { if (this.reportType.equals("Chart")) {
baseDataValidator baseDataValidator.reset().parameter("reportSubType").value(this.reportSubType)
.reset() .cantBeBlankWhenParameterProvidedIs("reportType", this.reportType)
.parameter("reportSubType")
.value(this.reportSubType)
.cantBeBlankWhenParameterProvidedIs("reportType",
this.reportType)
.isOneOfTheseValues(new Object[] { "Bar", "Pie" }); .isOneOfTheseValues(new Object[] { "Bar", "Pie" });
} else { } else {
baseDataValidator baseDataValidator.reset().parameter("reportSubType").value(this.reportSubType)
.reset() .mustBeBlankWhenParameterProvidedIs("reportType", this.reportType);
.parameter("reportSubType")
.value(this.reportSubType)
.mustBeBlankWhenParameterProvidedIs("reportType",
this.reportType);
} }
} }
baseDataValidator.reset().parameter("reportCategory") baseDataValidator.reset().parameter("reportCategory").value(this.reportCategory).notExceedingLengthOf(45);
.value(this.reportCategory).notExceedingLengthOf(45);
if (StringUtils.isNotBlank(this.reportType)) { if (StringUtils.isNotBlank(this.reportType)) {
if ((this.reportType.equals("Table")) if ((this.reportType.equals("Table")) || (this.reportType.equals("Chart"))) {
|| (this.reportType.equals("Chart"))) { baseDataValidator.reset().parameter("reportSql").value(this.reportSql)
baseDataValidator .cantBeBlankWhenParameterProvidedIs("reportType", this.reportType);
.reset()
.parameter("reportSql")
.value(this.reportSql)
.cantBeBlankWhenParameterProvidedIs("reportType",
this.reportType);
} else { } else {
baseDataValidator baseDataValidator.reset().parameter("reportSql").value(this.reportSql)
.reset() .mustBeBlankWhenParameterProvidedIs("reportType", this.reportType);
.parameter("reportSql")
.value(this.reportSql)
.mustBeBlankWhenParameterProvidedIs("reportType",
this.reportType);
} }
} }
throwExceptionIfValidationWarningsExist(dataValidationErrors); throwExceptionIfValidationWarningsExist(dataValidationErrors);
} }
private void throwExceptionIfValidationWarningsExist( private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) {
final List<ApiParameterError> dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); }
if (!dataValidationErrors.isEmpty()) {
throw new PlatformApiDataValidationException(
"validation.msg.validation.errors.exist",
"Validation errors exist.", dataValidationErrors);
}
} }
public String getReportName() { public String getReportName() {
return reportName; return reportName;
} }
public Set<ReportParameterUsage> getReportParameterUsages() { public boolean update(final Set<ReportParameterUsage> newReportParameterUsages) {
return reportParameterUsages; if (newReportParameterUsages == null) return false;
}
public void setReportParameterUsages(
Set<ReportParameterUsage> reportParameterUsages) {
this.reportParameterUsages = reportParameterUsages;
}
public boolean update(
final Set<ReportParameterUsage> newReportParameterUsages) {
if (newReportParameterUsages == null)
return false;
boolean updated = false; boolean updated = false;
@@ -305,52 +245,10 @@ public class Report extends AbstractPersistable<Long> {
return updated; return updated;
} }
private boolean changeInReportParameters( private boolean changeInReportParameters(final Set<ReportParameterUsage> newReportParameterUsages) {
Set<ReportParameterUsage> newReportParameterUsages) {
if (!(this.reportParameterUsages.equals(newReportParameterUsages))) return true; if (!(this.reportParameterUsages.equals(newReportParameterUsages))) return true;
Map<Long, ReportParameterUsage> currentRPUs = new HashMap<Long, ReportParameterUsage>();
for (ReportParameterUsage rpu : this.reportParameterUsages) {
currentRPUs.put(rpu.getId(), rpu);
}
Map<Long, ReportParameterUsage> newRPUs = new HashMap<Long, ReportParameterUsage>();
for (ReportParameterUsage rpu : newReportParameterUsages) {
newRPUs.put(rpu.getId(), rpu);
}
ReportParameterUsage currentRPU = null;
ReportParameterUsage newRPU = null;
for (Long key : currentRPUs.keySet()) {
currentRPU = currentRPUs.get(key);
newRPU = newRPUs.get(key);
if (existingEntryChanged(currentRPU, newRPU)) return true;
}
return false; return false;
} }
private boolean existingEntryChanged(
final ReportParameterUsage currentRPU, final ReportParameterUsage newRPU) {
if (!(currentRPU.getParameter().getId()
.equals(newRPU.getParameter().getId())))
return true;
if ((currentRPU.getReportParameterName() == null)
&& (newRPU.getReportParameterName() == null))
return false;
if (!(currentRPU.getReportParameterName()
.equals(newRPU.getReportParameterName())))
return true;
return false;
}
} }
@@ -18,4 +18,7 @@ public class ReportParameter extends AbstractPersistable<Long> {
// //
} }
public boolean hasIdOf(final Long id) {
return getId().equals(id);
}
} }
@@ -11,23 +11,22 @@ import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import javax.persistence.ManyToOne;
import javax.persistence.Table; import javax.persistence.Table;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.springframework.data.jpa.domain.AbstractPersistable; import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity @Entity
@Table(name = "stretchy_report_parameter") @Table(name = "stretchy_report_parameter")
public class ReportParameterUsage extends AbstractPersistable<Long> { public final class ReportParameterUsage extends AbstractPersistable<Long> {
@SuppressWarnings("unused")
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "report_id", nullable = false) @JoinColumn(name = "report_id", nullable = false)
private Report report; private Report report;
@SuppressWarnings("unused")
@ManyToOne(optional = false) @ManyToOne(optional = false)
@JoinColumn(name = "parameter_id", nullable = false) @JoinColumn(name = "parameter_id", nullable = false)
private ReportParameter parameter; private ReportParameter parameter;
@SuppressWarnings("unused")
@Column(name = "report_parameter_name") @Column(name = "report_parameter_name")
private String reportParameterName; private String reportParameterName;
@@ -35,39 +34,45 @@ public class ReportParameterUsage extends AbstractPersistable<Long> {
// //
} }
public ReportParameterUsage(final Report report, public ReportParameterUsage(final Report report, final ReportParameter parameter, final String reportParameterName) {
final ReportParameter parameter, final String reportParameterName) {
this.report = report; this.report = report;
this.parameter = parameter; this.parameter = parameter;
this.reportParameterName = reportParameterName; this.reportParameterName = reportParameterName;
} }
public ReportParameterUsage(final ReportParameterUsage currentReportParameterUsage, final Report report, @Override
final ReportParameter parameter, final String reportParameterName) { public boolean equals(final Object obj) {
this.setId(currentReportParameterUsage.getId()); if (obj == null) { return false; }
this.report = report; if (obj == this) { return true; }
this.parameter = parameter; if (obj.getClass() != getClass()) { return false; }
this.reportParameterName = reportParameterName; ReportParameterUsage rhs = (ReportParameterUsage) obj;
return new EqualsBuilder().appendSuper(super.equals(obj)) //
.append(this.getId(), rhs.getId()) //
.append(this.report.getId(), rhs.report.getId()) //
.append(this.parameter.getId(), rhs.parameter.getId()) //
.append(this.reportParameterName, rhs.reportParameterName) //
.isEquals();
} }
public void setReport(Report report) { @Override
this.report = report; public int hashCode() {
return new HashCodeBuilder(3, 5) //
.append(this.getId()) //
.append(this.report.getId()) //
.append(this.parameter.getId()) //
.append(this.reportParameterName) //
.toHashCode();
} }
public void setParameter(ReportParameter parameter) { public boolean hasIdOf(final Long id) {
this.parameter = parameter; return getId().equals(id);
} }
public ReportParameter getParameter() { public boolean hasParameterIdOf(final Long parameterId) {
return parameter; return this.parameter != null && this.parameter.hasIdOf(parameterId);
} }
public String getReportParameterName() { public void updateParameterName(final String parameterName) {
return reportParameterName; this.reportParameterName = parameterName;
} }
public void setReportParameterName(String reportParameterName) {
this.reportParameterName = reportParameterName;
}
} }
@@ -0,0 +1,14 @@
/**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.infrastructure.dataqueries.domain;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface ReportParameterUsageRepository extends JpaRepository<ReportParameterUsage, Long>,
JpaSpecificationExecutor<ReportParameterUsage> {
// no added behaviour
}
@@ -9,6 +9,7 @@ import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.api.JsonCommand; import org.mifosplatform.infrastructure.core.api.JsonCommand;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResult; import org.mifosplatform.infrastructure.core.data.CommandProcessingResult;
import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder; import org.mifosplatform.infrastructure.core.data.CommandProcessingResultBuilder;
@@ -17,6 +18,7 @@ import org.mifosplatform.infrastructure.dataqueries.domain.Report;
import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameter; import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameter;
import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameterRepository; import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameterRepository;
import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameterUsage; import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameterUsage;
import org.mifosplatform.infrastructure.dataqueries.domain.ReportParameterUsageRepository;
import org.mifosplatform.infrastructure.dataqueries.domain.ReportRepository; import org.mifosplatform.infrastructure.dataqueries.domain.ReportRepository;
import org.mifosplatform.infrastructure.dataqueries.exception.ReportNotFoundException; import org.mifosplatform.infrastructure.dataqueries.exception.ReportNotFoundException;
import org.mifosplatform.infrastructure.dataqueries.exception.ReportParameterNotFoundException; import org.mifosplatform.infrastructure.dataqueries.exception.ReportParameterNotFoundException;
@@ -36,29 +38,27 @@ import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@Service @Service
public class ReportWritePlatformServiceImpl implements public class ReportWritePlatformServiceImpl implements ReportWritePlatformService {
ReportWritePlatformService {
private final static Logger logger = LoggerFactory private final static Logger logger = LoggerFactory.getLogger(ReportWritePlatformServiceImpl.class);
.getLogger(ReportWritePlatformServiceImpl.class);
private final PlatformSecurityContext context; private final PlatformSecurityContext context;
private final ReportCommandFromApiJsonDeserializer fromApiJsonDeserializer; private final ReportCommandFromApiJsonDeserializer fromApiJsonDeserializer;
private final PermissionRepository permissionRepository;
private final ReportRepository reportRepository; private final ReportRepository reportRepository;
private final ReportParameterUsageRepository reportParameterUsageRepository;
private final ReportParameterRepository reportParameterRepository; private final ReportParameterRepository reportParameterRepository;
private final PermissionRepository permissionRepository;
@Autowired @Autowired
public ReportWritePlatformServiceImpl( public ReportWritePlatformServiceImpl(final PlatformSecurityContext context,
final PlatformSecurityContext context, final ReportCommandFromApiJsonDeserializer fromApiJsonDeserializer, final ReportRepository reportRepository,
final ReportCommandFromApiJsonDeserializer fromApiJsonDeserializer, final ReportParameterRepository reportParameterRepository, final ReportParameterUsageRepository reportParameterUsageRepository,
final ReportRepository reportRepository,
final ReportParameterRepository reportParameterRepository,
final PermissionRepository permissionRepository) { final PermissionRepository permissionRepository) {
this.context = context; this.context = context;
this.fromApiJsonDeserializer = fromApiJsonDeserializer; this.fromApiJsonDeserializer = fromApiJsonDeserializer;
this.reportRepository = reportRepository; this.reportRepository = reportRepository;
this.reportParameterRepository = reportParameterRepository; this.reportParameterRepository = reportParameterRepository;
this.reportParameterUsageRepository = reportParameterUsageRepository;
this.permissionRepository = permissionRepository; this.permissionRepository = permissionRepository;
} }
@@ -72,20 +72,18 @@ public class ReportWritePlatformServiceImpl implements
this.fromApiJsonDeserializer.validate(command.json()); this.fromApiJsonDeserializer.validate(command.json());
final Report report = Report.fromJson(command); final Report report = Report.fromJson(command);
final Set<ReportParameterUsage> reportParameterUsages = assembleSetOfReportParameterUsages( final Set<ReportParameterUsage> reportParameterUsages = assembleSetOfReportParameterUsages(report, command);
report, command); report.update(reportParameterUsages);
if (reportParameterUsages != null) {
report.setReportParameterUsages(reportParameterUsages);
}
this.reportRepository.save(report); this.reportRepository.save(report);
final Permission permission = new Permission("report", final Permission permission = new Permission("report", report.getReportName(), "READ");
report.getReportName(), "READ");
this.permissionRepository.save(permission); this.permissionRepository.save(permission);
return new CommandProcessingResultBuilder() return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) .withCommandId(command.commandId()) //
.withEntityId(report.getId()).build(); .withEntityId(report.getId()) //
.build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleReportDataIntegrityIssues(command, dve); handleReportDataIntegrityIssues(command, dve);
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
@@ -94,8 +92,7 @@ public class ReportWritePlatformServiceImpl implements
@Transactional @Transactional
@Override @Override
public CommandProcessingResult updateReport(final Long reportId, public CommandProcessingResult updateReport(final Long reportId, final JsonCommand command) {
final JsonCommand command) {
try { try {
context.authenticatedUser(); context.authenticatedUser();
@@ -103,15 +100,12 @@ public class ReportWritePlatformServiceImpl implements
this.fromApiJsonDeserializer.validate(command.json()); this.fromApiJsonDeserializer.validate(command.json());
final Report report = this.reportRepository.findOne(reportId); final Report report = this.reportRepository.findOne(reportId);
if (report == null) { if (report == null) { throw new ReportNotFoundException(reportId); }
throw new ReportNotFoundException(reportId);
}
final Map<String, Object> changes = report.update(command); final Map<String, Object> changes = report.update(command);
if (changes.containsKey("reportParameters")) { if (changes.containsKey("reportParameters")) {
final Set<ReportParameterUsage> reportParameterUsages = assembleSetOfReportParameterUsages( final Set<ReportParameterUsage> reportParameterUsages = assembleSetOfReportParameterUsages(report, command);
report, command);
boolean updated = report.update(reportParameterUsages); boolean updated = report.update(reportParameterUsages);
if (!updated) { if (!updated) {
changes.remove("reportParameters"); changes.remove("reportParameters");
@@ -122,9 +116,11 @@ public class ReportWritePlatformServiceImpl implements
this.reportRepository.saveAndFlush(report); this.reportRepository.saveAndFlush(report);
} }
return new CommandProcessingResultBuilder() return new CommandProcessingResultBuilder() //
.withCommandId(command.commandId()) .withCommandId(command.commandId()) //
.withEntityId(report.getId()).with(changes).build(); .withEntityId(report.getId()) //
.with(changes) //
.build();
} catch (DataIntegrityViolationException dve) { } catch (DataIntegrityViolationException dve) {
handleReportDataIntegrityIssues(command, dve); handleReportDataIntegrityIssues(command, dve);
return CommandProcessingResult.empty(); return CommandProcessingResult.empty();
@@ -136,27 +132,21 @@ public class ReportWritePlatformServiceImpl implements
public CommandProcessingResult deleteReport(final Long reportId) { public CommandProcessingResult deleteReport(final Long reportId) {
final Report report = this.reportRepository.findOne(reportId); final Report report = this.reportRepository.findOne(reportId);
if (report == null) { if (report == null) { throw new ReportNotFoundException(reportId); }
throw new ReportNotFoundException(reportId);
}
if (report.isCoreReport()) { if (report.isCoreReport()) {
throw new PlatformDataIntegrityException( //
"error.msg.cant.delete.core.report", throw new PlatformDataIntegrityException("error.msg.cant.delete.core.report", "Core Reports Can't be Deleted", "");
"Core Reports Can't be Deleted", "");
} }
final Permission permission = this.permissionRepository final Permission permission = this.permissionRepository.findOneByCode("READ" + "_" + report.getReportName());
.findOneByCode("READ" + "_" + report.getReportName()); if (permission == null) { throw new PermissionNotFoundException("READ" + "_" + report.getReportName()); }
if (permission == null) {
throw new PermissionNotFoundException("READ" + "_"
+ report.getReportName());
}
this.reportRepository.delete(report); this.reportRepository.delete(report);
this.permissionRepository.delete(permission); this.permissionRepository.delete(permission);
return new CommandProcessingResultBuilder().withEntityId(reportId) return new CommandProcessingResultBuilder() //
.withEntityId(reportId) //
.build(); .build();
} }
@@ -164,126 +154,88 @@ public class ReportWritePlatformServiceImpl implements
* Guaranteed to throw an exception no matter what the data integrity issue * Guaranteed to throw an exception no matter what the data integrity issue
* is. * is.
*/ */
private void handleReportDataIntegrityIssues(final JsonCommand command, private void handleReportDataIntegrityIssues(final JsonCommand command, final DataIntegrityViolationException dve) {
DataIntegrityViolationException dve) {
Throwable realCause = dve.getMostSpecificCause(); Throwable realCause = dve.getMostSpecificCause();
if (realCause.getMessage().contains("unq_report_name")) { if (realCause.getMessage().contains("unq_report_name")) {
final String name = command final String name = command.stringValueOfParameterNamed("reportName");
.stringValueOfParameterNamed("reportName"); throw new PlatformDataIntegrityException("error.msg.report.duplicate.name", "A report with name '" + name + "' already exists",
throw new PlatformDataIntegrityException( "name", name);
"error.msg.report.duplicate.name", "A report with name '"
+ name + "' already exists", "name", name);
} }
logger.error(dve.getMessage(), dve); logger.error(dve.getMessage(), dve);
throw new PlatformDataIntegrityException( throw new PlatformDataIntegrityException("error.msg.report.unknown.data.integrity.issue",
"error.msg.report.unknown.data.integrity.issue", "Unknown data integrity issue with resource: " + realCause.getMessage());
"Unknown data integrity issue with resource: "
+ realCause.getMessage());
} }
private Set<ReportParameterUsage> assembleSetOfReportParameterUsages( private Set<ReportParameterUsage> assembleSetOfReportParameterUsages(final Report report, final JsonCommand command) {
final Report report, final JsonCommand command) {
if (report == null) { Set<ReportParameterUsage> reportParameterUsages = null;
throw new PlatformDataIntegrityException("system.error",
"report parameter is null; ");
}
if (command.parameterExists("reportParameters")) { if (command.parameterExists("reportParameters")) {
Set<ReportParameterUsage> reportParameterUsages = new HashSet<ReportParameterUsage>(); JsonArray reportParametersArray = command.arrayOfParameterNamed("reportParameters");
JsonArray reportParametersArray = command
.arrayOfParameterNamed("reportParameters");
if (reportParametersArray != null) { if (reportParametersArray != null) {
reportParameterUsages = new HashSet<ReportParameterUsage>();
for (int i = 0; i < reportParametersArray.size(); i++) { for (int i = 0; i < reportParametersArray.size(); i++) {
final JsonObject jsonObject = reportParametersArray.get(i) final JsonObject jsonObject = reportParametersArray.get(i).getAsJsonObject();
.getAsJsonObject();
Long id = null; Long id = null;
ReportParameter parameter = null; ReportParameterUsage reportParameterUsageItem = null;
ReportParameter reportParameter = null;
String reportParameterName = null; String reportParameterName = null;
if (jsonObject.has("id")) {
final String idStr = jsonObject.get("id").getAsString();
if (StringUtils.isNotBlank(idStr)) {
id = Long.parseLong(idStr);
}
}
if (id != null) {
// existing report parameter usage
reportParameterUsageItem = this.reportParameterUsageRepository.findOne(id);
if (reportParameterUsageItem == null) { throw new ReportParameterNotFoundException(id); }
// check parameter
if (jsonObject.has("parameterId")) { if (jsonObject.has("parameterId")) {
final Long parameterId = jsonObject.get("parameterId") final Long parameterId = jsonObject.get("parameterId").getAsLong();
.getAsLong(); reportParameter = this.reportParameterRepository.findOne(parameterId);
parameter = this.reportParameterRepository if (reportParameter == null || !reportParameterUsageItem.hasParameterIdOf(parameterId)) {
.findOne(parameterId); //
if (parameter == null) { throw new ReportParameterNotFoundException(parameterId);
throw new ReportParameterNotFoundException( }
parameterId); }
if (jsonObject.has("reportParameterName")) {
reportParameterName = jsonObject.get("reportParameterName").getAsString();
reportParameterUsageItem.updateParameterName(reportParameterName);
} }
} else { } else {
throw new PlatformDataIntegrityException( // new report parameter usage
"error.msg.parameter.id.mandatory.in.report.parameter", if (jsonObject.has("parameterId")) {
final Long parameterId = jsonObject.get("parameterId").getAsLong();
reportParameter = this.reportParameterRepository.findOne(parameterId);
if (reportParameter == null) { throw new ReportParameterNotFoundException(parameterId); }
} else {
throw new PlatformDataIntegrityException("error.msg.parameter.id.mandatory.in.report.parameter",
"parameterId column is mandatory in Report Parameter Entry"); "parameterId column is mandatory in Report Parameter Entry");
} }
if (jsonObject.has("reportParameterName")) { if (jsonObject.has("reportParameterName")) {
reportParameterName = jsonObject.get( reportParameterName = jsonObject.get("reportParameterName").getAsString();
"reportParameterName").getAsString();
} }
if (jsonObject.has("id")) { reportParameterUsageItem = new ReportParameterUsage(report, reportParameter, reportParameterName);
final String idStr = jsonObject.get("id").getAsString();
if (!(idStr.equals("")))
id = Long.parseLong(idStr);
} }
ReportParameterUsage reportParameterUsage = null; reportParameterUsages.add(reportParameterUsageItem);
if (id == null) { }
reportParameterUsage = new ReportParameterUsage(report,
parameter, reportParameterName);
} else {
ReportParameterUsage currentReportParameterUsage = rpuById(
report, id);
if (existingEntryChanged(currentReportParameterUsage,
parameter.getId(), reportParameterName)) {
reportParameterUsage = new ReportParameterUsage(
currentReportParameterUsage, report,
parameter, reportParameterName);
} else {
reportParameterUsage = currentReportParameterUsage;
} }
} }
reportParameterUsages.add(reportParameterUsage);
}
return reportParameterUsages; return reportParameterUsages;
} else
return null;
} else
return null;
}
private boolean existingEntryChanged(
final ReportParameterUsage currentReportParameterUsage,
final Long parameterId, final String reportParameterName) {
if (!(currentReportParameterUsage.getParameter().getId()
.equals(parameterId)))
return true;
if ((reportParameterName == null)
&& (currentReportParameterUsage.getReportParameterName() == null))
return false;
if (!(currentReportParameterUsage.getReportParameterName()
.equals(reportParameterName)))
return true;
return false;
}
private ReportParameterUsage rpuById(final Report report, final Long id) {
for (ReportParameterUsage rpu : report.getReportParameterUsages()) {
if (rpu.getId().equals(id))
return rpu;
}
throw new PlatformDataIntegrityException(
"error.msg.supplied.parameter.id.doesnt.exist",
"Supplied parameterId column doesn't Exist", id);
} }
} }