diff --git a/HIRS_AttestationCA/build.gradle b/HIRS_AttestationCA/build.gradle index cbed0273c..6f7736e6b 100644 --- a/HIRS_AttestationCA/build.gradle +++ b/HIRS_AttestationCA/build.gradle @@ -43,7 +43,7 @@ war.dependsOn copyVersion ext.configDir = new File(projectDir, 'config') ext.checkstyleConfigDir = "$configDir/checkstyle" checkstyle { - toolVersion = '8.10.1' + toolVersion = '8.45.1' configFile = checkstyleConfigFile configProperties.put('basedir', checkstyleConfigDir) ignoreFailures = false diff --git a/HIRS_AttestationCA/src/test/java/hirs/attestationca/IssuedCertificateAttributeHelperTest.java b/HIRS_AttestationCA/src/test/java/hirs/attestationca/IssuedCertificateAttributeHelperTest.java index f3fae92a0..5852b817d 100644 --- a/HIRS_AttestationCA/src/test/java/hirs/attestationca/IssuedCertificateAttributeHelperTest.java +++ b/HIRS_AttestationCA/src/test/java/hirs/attestationca/IssuedCertificateAttributeHelperTest.java @@ -1,8 +1,8 @@ package hirs.attestationca; -import org.bouncycastle.asn1.DERSequence; -import org.bouncycastle.asn1.DERSet; -import org.bouncycastle.asn1.DERTaggedObject; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1Set; +import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DLSequence; import org.bouncycastle.asn1.x509.Extension; import org.testng.annotations.Test; @@ -188,16 +188,16 @@ private Map getSubjectAlternativeNameAttributes( Map subjectAlternativeNameAttrMap = new HashMap<>(); DLSequence dlSequence = (DLSequence) subjectAlternativeName.getParsedValue(); - DERTaggedObject derTaggedObject = (DERTaggedObject) dlSequence.getObjectAt(0); - DERSequence derSequence = (DERSequence) derTaggedObject.getObject(); + ASN1TaggedObject asn1TaggedObject = (ASN1TaggedObject) dlSequence.getObjectAt(0); + ASN1Sequence asn1Sequence = (ASN1Sequence) asn1TaggedObject.getObject(); - Enumeration enumeration = derSequence.getObjects(); + Enumeration enumeration = asn1Sequence.getObjects(); while (enumeration.hasMoreElements()) { - DERSet set = (DERSet) enumeration.nextElement(); - DERSequence innerDerSequence = (DERSequence) set.getObjectAt(0); + ASN1Set set = (ASN1Set) enumeration.nextElement(); + ASN1Sequence innerAsn1Sequence = (ASN1Sequence) set.getObjectAt(0); - subjectAlternativeNameAttrMap.put(innerDerSequence.getObjectAt(0).toString(), - innerDerSequence.getObjectAt(1).toString()); + subjectAlternativeNameAttrMap.put(innerAsn1Sequence.getObjectAt(0).toString(), + innerAsn1Sequence.getObjectAt(1).toString()); } return subjectAlternativeNameAttrMap; } diff --git a/HIRS_AttestationCAPortal/build.gradle b/HIRS_AttestationCAPortal/build.gradle index 005221d13..25f2c3140 100644 --- a/HIRS_AttestationCAPortal/build.gradle +++ b/HIRS_AttestationCAPortal/build.gradle @@ -77,7 +77,7 @@ ext.configDir = new File(projectDir, 'config') ext.checkstyleConfigDir = "$configDir/checkstyle" checkstyle { - toolVersion = '8.10.1' + toolVersion = '8.45.1' configFile = checkstyleConfigFile configProperties.put('basedir', checkstyleConfigDir) ignoreFailures = false diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java index f2a5b36eb..e250384a1 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/datatables/package-info.java @@ -1,9 +1,9 @@ -/** - * This packages provides classes to serve jQuery dataTable requests. - * - * DataTableInput, Column, Order, and Search from: - * https://github.com/darrachequesne/spring-data-jpa-datatables - * - * The rest of the package was unnecessary and introduced dependency conflicts. - */ -package hirs.attestationca.portal.datatables; +/** + * This packages provides classes to serve jQuery dataTable requests. + * + * DataTableInput, Column, Order, and Search from: + * https://github.com/darrachequesne/spring-data-jpa-datatables + * + * The rest of the package was unnecessary and introduced dependency conflicts. + */ +package hirs.attestationca.portal.datatables; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/model/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/model/package-info.java index ccb9c352b..84140771c 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/model/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/model/package-info.java @@ -1,4 +1,4 @@ -/** - * This packages provides data model classes for the HIRS Attestation CA portal. - */ -package hirs.attestationca.portal.model; +/** + * This packages provides data model classes for the HIRS Attestation CA portal. + */ +package hirs.attestationca.portal.model; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/package-info.java index e45b219af..1fa641aab 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/package-info.java @@ -1,4 +1,4 @@ -/** - * Root Package for HIRS Attestation CA Portal. - */ -package hirs.attestationca.portal; +/** + * Root Package for HIRS Attestation CA Portal. + */ +package hirs.attestationca.portal; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java index a3f9dcb3b..bb6aef045 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/controllers/package-info.java @@ -1,4 +1,4 @@ -/** - * This package contains PageController implementations. - */ -package hirs.attestationca.portal.page.controllers; +/** + * This package contains PageController implementations. + */ +package hirs.attestationca.portal.page.controllers; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java index 16d73cef1..5af3cbc83 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/package-info.java @@ -1,4 +1,4 @@ -/** - * This package provides interfaces and superclasses for PageController and associated objects. - */ -package hirs.attestationca.portal.page; +/** + * This package provides interfaces and superclasses for PageController and associated objects. + */ +package hirs.attestationca.portal.page; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java index 4dd1c58a9..db85fbe02 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/page/params/package-info.java @@ -1,4 +1,4 @@ -/** - * This package contains url parameter classes for portal pages. - */ -package hirs.attestationca.portal.page.params; +/** + * This package contains url parameter classes for portal pages. + */ +package hirs.attestationca.portal.page.params; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/persistence/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/persistence/package-info.java index 6509ebac3..ec5f08720 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/persistence/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/persistence/package-info.java @@ -1,4 +1,4 @@ -/** - * Persistence related classes for Attestation CA Portal. - */ -package hirs.attestationca.portal.persistence; +/** + * Persistence related classes for Attestation CA Portal. + */ +package hirs.attestationca.portal.persistence; diff --git a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/util/package-info.java b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/util/package-info.java index e8de1d1db..ba8e2d99a 100644 --- a/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/util/package-info.java +++ b/HIRS_AttestationCAPortal/src/main/java/hirs/attestationca/portal/util/package-info.java @@ -1,4 +1,4 @@ -/** - * Utilities classes for the Attestation CA Portal. - */ -package hirs.attestationca.portal.util; +/** + * Utilities classes for the Attestation CA Portal. + */ +package hirs.attestationca.portal.util; diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java index cfb624bdb..a91201d32 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/controllers/package-info.java @@ -1,4 +1,4 @@ -/** - * This package contains unit tests for PageController implementations. - */ -package hirs.attestationca.portal.page.controllers; +/** + * This package contains unit tests for PageController implementations. + */ +package hirs.attestationca.portal.page.controllers; diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/datatables/package-info.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/datatables/package-info.java index 504f67d45..67d50b998 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/datatables/package-info.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/datatables/package-info.java @@ -1,4 +1,4 @@ -/** - * This package contains unit tests for the datatables adapter java classes. - */ -package hirs.attestationca.portal.page.datatables; +/** + * This package contains unit tests for the datatables adapter java classes. + */ +package hirs.attestationca.portal.page.datatables; diff --git a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java index 0fad830d0..352716aee 100644 --- a/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java +++ b/HIRS_AttestationCAPortal/src/test/java/hirs/attestationca/portal/page/package-info.java @@ -1,4 +1,4 @@ -/** - * This package contains unit tests for base page classes. - */ -package hirs.attestationca.portal.page; +/** + * This package contains unit tests for base page classes. + */ +package hirs.attestationca.portal.page; diff --git a/HIRS_Provisioner/build.gradle b/HIRS_Provisioner/build.gradle index ea3111d19..9b2cc628a 100644 --- a/HIRS_Provisioner/build.gradle +++ b/HIRS_Provisioner/build.gradle @@ -32,7 +32,7 @@ jar.dependsOn copyVersion ext.configDir = new File(projectDir, 'config') ext.checkstyleConfigDir = "$configDir/checkstyle" checkstyle { - toolVersion = '5.7' + toolVersion = '8.45.1' configFile = checkstyleConfigFile configProperties.put('basedir', checkstyleConfigDir) ignoreFailures = false diff --git a/HIRS_Provisioner/src/main/java/hirs/provisioner/package-info.java b/HIRS_Provisioner/src/main/java/hirs/provisioner/package-info.java index f9f484e26..93870b524 100644 --- a/HIRS_Provisioner/src/main/java/hirs/provisioner/package-info.java +++ b/HIRS_Provisioner/src/main/java/hirs/provisioner/package-info.java @@ -1,4 +1,4 @@ -/** - * This package defines the application entry points. - */ -package hirs.provisioner; +/** + * This package defines the application entry points. + */ +package hirs.provisioner; diff --git a/HIRS_Structs/build.gradle b/HIRS_Structs/build.gradle index 7f1bb6759..bcd27c0e3 100644 --- a/HIRS_Structs/build.gradle +++ b/HIRS_Structs/build.gradle @@ -14,7 +14,6 @@ dependencies { ext.configDir = new File(projectDir, 'config') ext.checkstyleConfigDir = "$configDir/checkstyle" -//ext.checkstyleConfigDir = "$rootProject.projectDir/config/checkstyle" checkstyle { toolVersion = '8.45.1' diff --git a/HIRS_Utils/build.gradle b/HIRS_Utils/build.gradle index e041e015d..34874f488 100644 --- a/HIRS_Utils/build.gradle +++ b/HIRS_Utils/build.gradle @@ -99,7 +99,7 @@ task integrationTest(type: Test) { ext.checkstyleConfigDir = "$configDir/checkstyle" checkstyle { - toolVersion = '8.10.1' + toolVersion = '8.45.1' configFile = checkstyleConfigFile configProperties.put('basedir', checkstyleConfigDir) ignoreFailures = false diff --git a/HIRS_Utils/src/main/java/hirs/IMAReportRequest.java b/HIRS_Utils/src/main/java/hirs/IMAReportRequest.java index 92fd1609e..25c5f2bfe 100755 --- a/HIRS_Utils/src/main/java/hirs/IMAReportRequest.java +++ b/HIRS_Utils/src/main/java/hirs/IMAReportRequest.java @@ -1,102 +1,102 @@ -package hirs; - -import static org.apache.logging.log4j.LogManager.getLogger; -import hirs.data.persist.IMAReport; -import hirs.data.persist.Report; - -import javax.xml.bind.annotation.XmlElement; - -import org.apache.logging.log4j.Logger; - -/** - * IMAReportRequest is an immutable class and extends - * ReportRequest to specify parameters which define - * the composition of the IMA report to be generated by the client. - * For example, IMAReportRequest specifies whether a full IMA - * report should be generated and submitted for appraisal or whether a delta - * report (containing new entries since last full report) should be generated - * and submitted. If a delta report is being requested, then an index must be - * provided which is used to inform the client which subset of measurements - * to include in the report. - */ -public final class IMAReportRequest implements ReportRequest { - - private static final Logger LOGGER = getLogger(IMAReportRequest.class); - - @XmlElement - private final String bootcycleId; - - @XmlElement - private final int index; - - /** - * Default constructor required to enable marshalling and unmarshalling - * to/from xml. - */ - public IMAReportRequest() { - this(null, 0); - } - - /** - * Creates a new IMAReportRequest. The boot-cycle ID and index - * are set. The boot-cycle ID may be null to indicate that it is unknown by - * the appraiser and a full report should be sent. The index is the index of - * the new IMA record to send. An index of zero indicates a full report - * should be sent. - *

- * If the boot-cycle is null then the index must be zero. Otherwise an - * IllegalArgumentException is thrown. - * - * @param bootcycleId - * boot-cycle ID - * @param i - * value to use as IMA index - */ - public IMAReportRequest(final String bootcycleId, final int i) { - LOGGER.debug("Entering constructor"); - if (i >= 0) { - index = i; - } else { - String msg = "Cannot init IMAReportRequest with index less than 0"; - LOGGER.error(msg); - throw new IllegalArgumentException(msg); - } - if (bootcycleId == null && i != 0) { - String msg = "null boot-cycle ID must have index of 0"; - LOGGER.error(msg); - throw new IllegalArgumentException(msg); - } - this.bootcycleId = bootcycleId; - LOGGER.debug("Exiting constructor"); - } - - @Override - public Class getReportType() { - return IMAReport.class; - } - - /** - * Returns the boot-cycle ID. This is the last boot-cycle ID that was saved - * by the appraiser. If this is null or different than the boot-cycle ID for - * the collector then a full report shall be sent. - * - * @return boot-cycle ID - */ - public String getBootcycleId() { - return bootcycleId; - } - - /** - * Method returns the IMA index. - * @return index used to specify start location of measurement entries to - * include in IMA report - */ - public int getIMAIndex() { - return index; - } - - @Override - public String toString() { - return String.format("(%s, %d)", bootcycleId, index); - } -} +package hirs; + +import static org.apache.logging.log4j.LogManager.getLogger; +import hirs.data.persist.IMAReport; +import hirs.data.persist.Report; + +import javax.xml.bind.annotation.XmlElement; + +import org.apache.logging.log4j.Logger; + +/** + * IMAReportRequest is an immutable class and extends + * ReportRequest to specify parameters which define + * the composition of the IMA report to be generated by the client. + * For example, IMAReportRequest specifies whether a full IMA + * report should be generated and submitted for appraisal or whether a delta + * report (containing new entries since last full report) should be generated + * and submitted. If a delta report is being requested, then an index must be + * provided which is used to inform the client which subset of measurements + * to include in the report. + */ +public final class IMAReportRequest implements ReportRequest { + + private static final Logger LOGGER = getLogger(IMAReportRequest.class); + + @XmlElement + private final String bootcycleId; + + @XmlElement + private final int index; + + /** + * Default constructor required to enable marshalling and unmarshalling + * to/from xml. + */ + public IMAReportRequest() { + this(null, 0); + } + + /** + * Creates a new IMAReportRequest. The boot-cycle ID and index + * are set. The boot-cycle ID may be null to indicate that it is unknown by + * the appraiser and a full report should be sent. The index is the index of + * the new IMA record to send. An index of zero indicates a full report + * should be sent. + *

+ * If the boot-cycle is null then the index must be zero. Otherwise an + * IllegalArgumentException is thrown. + * + * @param bootcycleId + * boot-cycle ID + * @param i + * value to use as IMA index + */ + public IMAReportRequest(final String bootcycleId, final int i) { + LOGGER.debug("Entering constructor"); + if (i >= 0) { + index = i; + } else { + String msg = "Cannot init IMAReportRequest with index less than 0"; + LOGGER.error(msg); + throw new IllegalArgumentException(msg); + } + if (bootcycleId == null && i != 0) { + String msg = "null boot-cycle ID must have index of 0"; + LOGGER.error(msg); + throw new IllegalArgumentException(msg); + } + this.bootcycleId = bootcycleId; + LOGGER.debug("Exiting constructor"); + } + + @Override + public Class getReportType() { + return IMAReport.class; + } + + /** + * Returns the boot-cycle ID. This is the last boot-cycle ID that was saved + * by the appraiser. If this is null or different than the boot-cycle ID for + * the collector then a full report shall be sent. + * + * @return boot-cycle ID + */ + public String getBootcycleId() { + return bootcycleId; + } + + /** + * Method returns the IMA index. + * @return index used to specify start location of measurement entries to + * include in IMA report + */ + public int getIMAIndex() { + return index; + } + + @Override + public String toString() { + return String.format("(%s, %d)", bootcycleId, index); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/ReportRequest.java b/HIRS_Utils/src/main/java/hirs/ReportRequest.java index 6175a624e..aeb919ed0 100755 --- a/HIRS_Utils/src/main/java/hirs/ReportRequest.java +++ b/HIRS_Utils/src/main/java/hirs/ReportRequest.java @@ -1,30 +1,30 @@ -package hirs; - -import hirs.data.persist.Report; - -import javax.xml.bind.annotation.XmlSeeAlso; -import javax.xml.bind.annotation.XmlTransient; - -/** - * A ReportRequest is generated by the Appraiser and used to instruct the - * client to produce a particular report or set of reports. Reporting configuration parameters, such - * as the URL of the appraiser, are also specified in the ReportRequest. - *

- * This ReportRequest class contains minimal information because each report request is - * vastly different. The report type is used to specify the type of report to be generated by the - * client and submitted to the Appraiser for processing. - */ -@XmlTransient -@XmlSeeAlso(value = { IntegrityReportRequest.class, TPMReportRequest.class, IMAReportRequest.class, - DeviceInfoReportRequest.class }) -public interface ReportRequest { - - /** - * Returns a Report class that indicates the type of report requested. The report - * type is used to specify what report(s) the client is expected to generate and submit to the - * Appraiser for evaluation. - * - * @return report type - */ - Class getReportType(); -} +package hirs; + +import hirs.data.persist.Report; + +import javax.xml.bind.annotation.XmlSeeAlso; +import javax.xml.bind.annotation.XmlTransient; + +/** + * A ReportRequest is generated by the Appraiser and used to instruct the + * client to produce a particular report or set of reports. Reporting configuration parameters, such + * as the URL of the appraiser, are also specified in the ReportRequest. + *

+ * This ReportRequest class contains minimal information because each report request is + * vastly different. The report type is used to specify the type of report to be generated by the + * client and submitted to the Appraiser for processing. + */ +@XmlTransient +@XmlSeeAlso(value = { IntegrityReportRequest.class, TPMReportRequest.class, IMAReportRequest.class, + DeviceInfoReportRequest.class }) +public interface ReportRequest { + + /** + * Returns a Report class that indicates the type of report requested. The report + * type is used to specify what report(s) the client is expected to generate and submit to the + * Appraiser for evaluation. + * + * @return report type + */ + Class getReportType(); +} diff --git a/HIRS_Utils/src/main/java/hirs/config/package-info.java b/HIRS_Utils/src/main/java/hirs/config/package-info.java index dd78c4ed4..9b774fe8d 100644 --- a/HIRS_Utils/src/main/java/hirs/config/package-info.java +++ b/HIRS_Utils/src/main/java/hirs/config/package-info.java @@ -1,5 +1,5 @@ -/** - * This packages provides the classes necessary to load and read from the client - * configuration file. - */ -package hirs.config; +/** + * This packages provides the classes necessary to load and read from the client + * configuration file. + */ +package hirs.config; diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/AbstractEntity.java b/HIRS_Utils/src/main/java/hirs/data/persist/AbstractEntity.java index 6426ab846..228546591 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/AbstractEntity.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/AbstractEntity.java @@ -1,99 +1,99 @@ -package hirs.data.persist; - -import java.util.Date; -import java.util.UUID; - -import javax.persistence.Column; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.MappedSuperclass; -import org.hibernate.annotations.GenericGenerator; -import org.hibernate.annotations.Type; - -/** - * An abstract database entity. - */ -@MappedSuperclass -public abstract class AbstractEntity { - - /** - * static value for the length of a status message for objects that - * can have extremely long values, potentially. - */ - protected static final int RESULT_MESSAGE_LENGTH = 1000000; - - @Id - @Column(name = "id") - @GeneratedValue(generator = "uuid2") - @GenericGenerator(name = "uuid2", strategy = "uuid2") - @Type(type = "uuid-char") - private UUID id; - - @Column (name = "create_time") - private final Date createTime = new Date(); - - /** - * Default empty constructor is required for Hibernate. It is protected to - * prevent code from calling it directly. - */ - protected AbstractEntity() { - super(); - } - - /** - * Returns the unique ID associated with this entity. - * - * @return unique ID - */ - public UUID getId() { - return id; - } - - /** - * Returns the creation time of this entity. - * - * @return creation time - */ - public final Date getCreateTime() { - return (Date) createTime.clone(); - } - - /** - * Reset the creation time to the current time. - */ - public final void resetCreateTime() { - createTime.setTime(new Date().getTime()); - } - - @Override - public int hashCode() { - if (id != null) { - return id.hashCode(); - } - return super.hashCode(); - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (!(this.getClass().equals(obj.getClass()))) { - return false; - } - return this.hashCode() == obj.hashCode(); - } - - @Override - public String toString() { - try { - return String.format("UUID=%s, createTime=%s", - getId(), getCreateTime().toString()); - } catch (NullPointerException npEx) { - return ""; - } - } -} +package hirs.data.persist; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import org.hibernate.annotations.GenericGenerator; +import org.hibernate.annotations.Type; + +/** + * An abstract database entity. + */ +@MappedSuperclass +public abstract class AbstractEntity { + + /** + * static value for the length of a status message for objects that + * can have extremely long values, potentially. + */ + protected static final int RESULT_MESSAGE_LENGTH = 1000000; + + @Id + @Column(name = "id") + @GeneratedValue(generator = "uuid2") + @GenericGenerator(name = "uuid2", strategy = "uuid2") + @Type(type = "uuid-char") + private UUID id; + + @Column (name = "create_time") + private final Date createTime = new Date(); + + /** + * Default empty constructor is required for Hibernate. It is protected to + * prevent code from calling it directly. + */ + protected AbstractEntity() { + super(); + } + + /** + * Returns the unique ID associated with this entity. + * + * @return unique ID + */ + public UUID getId() { + return id; + } + + /** + * Returns the creation time of this entity. + * + * @return creation time + */ + public final Date getCreateTime() { + return (Date) createTime.clone(); + } + + /** + * Reset the creation time to the current time. + */ + public final void resetCreateTime() { + createTime.setTime(new Date().getTime()); + } + + @Override + public int hashCode() { + if (id != null) { + return id.hashCode(); + } + return super.hashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(this.getClass().equals(obj.getClass()))) { + return false; + } + return this.hashCode() == obj.hashCode(); + } + + @Override + public String toString() { + try { + return String.format("UUID=%s, createTime=%s", + getId(), getCreateTime().toString()); + } catch (NullPointerException npEx) { + return ""; + } + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/ArchivableEntity.java b/HIRS_Utils/src/main/java/hirs/data/persist/ArchivableEntity.java index ec0a11b22..30a0cd7c2 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/ArchivableEntity.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/ArchivableEntity.java @@ -1,127 +1,127 @@ -package hirs.data.persist; - -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; -import java.util.Date; - -/** - * An abstract archivable entity that can be deleted. - */ -@MappedSuperclass -public abstract class ArchivableEntity extends AbstractEntity { - - /** - * Defining the size of a message field for error display. - */ - public static final int MAX_MESSAGE_LENGTH = 2400; - - @Column(name = "archived_time") - private Date archivedTime; - - @Column(name = "archived_description") - private String archivedDescription; - - /** - * Default empty constructor is required for Hibernate. It is protected to - * prevent code from calling it directly. - */ - protected ArchivableEntity() { - super(); - } - - /** - * Return the boolean representing whether or not this entity has been soft-deleted. - * - * @return true if this entity has been soft-deleted, false otherwise - */ - public final boolean isArchived() { - return archivedTime != null; - } - - /** - * Signals that this entity has been archived, by setting the archivedTime to the current date - * and time. - * - * @return - * true if time was null and date was set. - * false is archived time is already set, signifying the entity has been archived. - */ - public final boolean archive() { - if (this.archivedTime == null) { - this.archivedTime = new Date(); - return true; - } - return false; - } - - /** - * Sets a description for the resolution if one is provided. This is done for accounting - * purposes so the reason for action taken can be referenced. - * - * @param description - description of the action taken for resolution - * @return - * boolean result is dependent on the return value of the archive() method - */ - public final boolean archive(final String description) { - if (archive()) { - this.archivedDescription = description; - return true; - } else { - return false; - } - } - - /** - * Sets the archivedTime to null. The archivedTime being null signifies that the entity has - * not been archived. If the time is already null then this call was unnecessary. - * - * @return - * true if the time is changed to null. - * false if time was already set to null. - */ - public final boolean restore() { - if (this.archivedTime != null) { - this.archivedTime = null; - this.archivedDescription = null; - return true; - } - return false; - } - - /** - * Returns the timestamp of when the entity was archived if applicable. If the - * entity has not been resolved, then null is returned. - * - * @return archivedTime - * If entity was archived, timestamp of the occurrence, null otherwise. - */ - public final Date getArchivedTime() { - if (archivedTime == null) { - return null; - } else { - return (Date) archivedTime.clone(); - } - } - - /** - * Returns the description of the action taken during resolution. The description can be null. - * - * @return - * description string of the action taken during resolution - */ - public final String getArchivedDescription() { - return this.archivedDescription; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(super.toString()); - if (archivedTime != null) { - sb.append(String.format(", archivedTime=%s, archiveDescription=%s", - archivedTime.toString(), archivedDescription)); - } - - return sb.toString(); - } -} +package hirs.data.persist; + +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; +import java.util.Date; + +/** + * An abstract archivable entity that can be deleted. + */ +@MappedSuperclass +public abstract class ArchivableEntity extends AbstractEntity { + + /** + * Defining the size of a message field for error display. + */ + public static final int MAX_MESSAGE_LENGTH = 2400; + + @Column(name = "archived_time") + private Date archivedTime; + + @Column(name = "archived_description") + private String archivedDescription; + + /** + * Default empty constructor is required for Hibernate. It is protected to + * prevent code from calling it directly. + */ + protected ArchivableEntity() { + super(); + } + + /** + * Return the boolean representing whether or not this entity has been soft-deleted. + * + * @return true if this entity has been soft-deleted, false otherwise + */ + public final boolean isArchived() { + return archivedTime != null; + } + + /** + * Signals that this entity has been archived, by setting the archivedTime to the current date + * and time. + * + * @return + * true if time was null and date was set. + * false is archived time is already set, signifying the entity has been archived. + */ + public final boolean archive() { + if (this.archivedTime == null) { + this.archivedTime = new Date(); + return true; + } + return false; + } + + /** + * Sets a description for the resolution if one is provided. This is done for accounting + * purposes so the reason for action taken can be referenced. + * + * @param description - description of the action taken for resolution + * @return + * boolean result is dependent on the return value of the archive() method + */ + public final boolean archive(final String description) { + if (archive()) { + this.archivedDescription = description; + return true; + } else { + return false; + } + } + + /** + * Sets the archivedTime to null. The archivedTime being null signifies that the entity has + * not been archived. If the time is already null then this call was unnecessary. + * + * @return + * true if the time is changed to null. + * false if time was already set to null. + */ + public final boolean restore() { + if (this.archivedTime != null) { + this.archivedTime = null; + this.archivedDescription = null; + return true; + } + return false; + } + + /** + * Returns the timestamp of when the entity was archived if applicable. If the + * entity has not been resolved, then null is returned. + * + * @return archivedTime + * If entity was archived, timestamp of the occurrence, null otherwise. + */ + public final Date getArchivedTime() { + if (archivedTime == null) { + return null; + } else { + return (Date) archivedTime.clone(); + } + } + + /** + * Returns the description of the action taken during resolution. The description can be null. + * + * @return + * description string of the action taken during resolution + */ + public final String getArchivedDescription() { + return this.archivedDescription; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()); + if (archivedTime != null) { + sb.append(String.format(", archivedTime=%s, archiveDescription=%s", + archivedTime.toString(), archivedDescription)); + } + + return sb.toString(); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/UserDefinedEntity.java b/HIRS_Utils/src/main/java/hirs/data/persist/UserDefinedEntity.java index 21fe1a449..716448a1c 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/UserDefinedEntity.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/UserDefinedEntity.java @@ -1,149 +1,149 @@ -package hirs.data.persist; - -import javax.persistence.Column; -import javax.persistence.MappedSuperclass; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -/** - * An abstract archivable entity that can be given a user-defined name and description. - */ -@MappedSuperclass -public abstract class UserDefinedEntity extends ArchivableEntity { - - private static final Logger LOGGER = LogManager.getLogger(UserDefinedEntity.class); - - @Column(nullable = false, unique = true) - private String name; - - @Column(nullable = false, unique = false) - private String description = ""; - - /** - * Default empty constructor is required for Hibernate. It is protected to - * prevent code from calling it directly. - */ - protected UserDefinedEntity() { - super(); - } - - /** - * Creates a new entity with the specified name. - * - * @param name name - */ - public UserDefinedEntity(final String name) { - this(name, ""); - } - - /** - * Creates a new Policy with the specified name and description. - * - * @param name - * name (required) - * @param description - * description (may be null) - */ - public UserDefinedEntity(final String name, final String description) { - setName(name); - setDescription(description); - } - - /** - * Returns the name of this entity. Names are unique and used by users to reference them. - * - * @return name - */ - public final String getName() { - return name; - } - - /** - * Sets the name of this entity. This name must be unique and - * will be used by users to retrieve and identify it. - * . - * - * @param name name - */ - public final void setName(final String name) { - if (name == null) { - LOGGER.debug("null name in setter"); - throw new NullPointerException("name"); - } - LOGGER.debug("setting name: {}", name); - this.name = name; - } - - /** - * Returns the description of this entity. Descriptions are not unique and - * are specifically used to provide additional details. - * - * @return description description - */ - public final String getDescription() { - return description; - } - - /** - * Sets the description of this entity. The description is not - * required and does not need to be unique. It is simply used to provide the - * user with more information about this entity. - * - * @param description description - */ - public final void setDescription(final String description) { - if (description == null) { - LOGGER.debug("null description in setter"); - throw new NullPointerException("description"); - } - LOGGER.debug("Setting description: {}", description); - this.description = description; - } - - /** - * Returns a boolean if other is equal to this. UserDefinedEntitys are - * identified by their name, so this returns true if other is - * an instance of UserDefinedEntity and its name is the same as this - * UserDefinedEntity. Otherwise this returns false. - * - * @param other - * other object to test for equals - * @return true if other is Baseline and has same name - */ - @Override - public boolean equals(final Object other) { - if (this == other) { - return true; - } - if (!(other instanceof UserDefinedEntity)) { - return false; - } - - final UserDefinedEntity entity = (UserDefinedEntity) other; - return this.getName().equals(entity.getName()); - } - - /** - * Returns the hash code for this UserDefinedEntity. - * UserDefinedEntitys are identified by their name, so the returned hash - * is the hash of the name. - * - * @return hash - */ - @Override - public int hashCode() { - return name.hashCode(); - } - - /** - * Returns a String representation of this class. This returns - * the UserDefinedEntity name. - * - * @return UserDefinedEntity name - */ - @Override - public String toString() { - return this.name; - } -} +package hirs.data.persist; + +import javax.persistence.Column; +import javax.persistence.MappedSuperclass; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * An abstract archivable entity that can be given a user-defined name and description. + */ +@MappedSuperclass +public abstract class UserDefinedEntity extends ArchivableEntity { + + private static final Logger LOGGER = LogManager.getLogger(UserDefinedEntity.class); + + @Column(nullable = false, unique = true) + private String name; + + @Column(nullable = false, unique = false) + private String description = ""; + + /** + * Default empty constructor is required for Hibernate. It is protected to + * prevent code from calling it directly. + */ + protected UserDefinedEntity() { + super(); + } + + /** + * Creates a new entity with the specified name. + * + * @param name name + */ + public UserDefinedEntity(final String name) { + this(name, ""); + } + + /** + * Creates a new Policy with the specified name and description. + * + * @param name + * name (required) + * @param description + * description (may be null) + */ + public UserDefinedEntity(final String name, final String description) { + setName(name); + setDescription(description); + } + + /** + * Returns the name of this entity. Names are unique and used by users to reference them. + * + * @return name + */ + public final String getName() { + return name; + } + + /** + * Sets the name of this entity. This name must be unique and + * will be used by users to retrieve and identify it. + * . + * + * @param name name + */ + public final void setName(final String name) { + if (name == null) { + LOGGER.debug("null name in setter"); + throw new NullPointerException("name"); + } + LOGGER.debug("setting name: {}", name); + this.name = name; + } + + /** + * Returns the description of this entity. Descriptions are not unique and + * are specifically used to provide additional details. + * + * @return description description + */ + public final String getDescription() { + return description; + } + + /** + * Sets the description of this entity. The description is not + * required and does not need to be unique. It is simply used to provide the + * user with more information about this entity. + * + * @param description description + */ + public final void setDescription(final String description) { + if (description == null) { + LOGGER.debug("null description in setter"); + throw new NullPointerException("description"); + } + LOGGER.debug("Setting description: {}", description); + this.description = description; + } + + /** + * Returns a boolean if other is equal to this. UserDefinedEntitys are + * identified by their name, so this returns true if other is + * an instance of UserDefinedEntity and its name is the same as this + * UserDefinedEntity. Otherwise this returns false. + * + * @param other + * other object to test for equals + * @return true if other is Baseline and has same name + */ + @Override + public boolean equals(final Object other) { + if (this == other) { + return true; + } + if (!(other instanceof UserDefinedEntity)) { + return false; + } + + final UserDefinedEntity entity = (UserDefinedEntity) other; + return this.getName().equals(entity.getName()); + } + + /** + * Returns the hash code for this UserDefinedEntity. + * UserDefinedEntitys are identified by their name, so the returned hash + * is the hash of the name. + * + * @return hash + */ + @Override + public int hashCode() { + return name.hashCode(); + } + + /** + * Returns a String representation of this class. This returns + * the UserDefinedEntity name. + * + * @return UserDefinedEntity name + */ + @Override + public String toString() { + return this.name; + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/baseline/Baseline.java b/HIRS_Utils/src/main/java/hirs/data/persist/baseline/Baseline.java index e502b277e..e3ed2ba1c 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/baseline/Baseline.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/baseline/Baseline.java @@ -1,83 +1,83 @@ -package hirs.data.persist.baseline; - -import hirs.data.persist.UserDefinedEntity; -import hirs.data.persist.enums.AlertSeverity; -import javax.persistence.Access; -import javax.persistence.AccessType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Inheritance; -import javax.persistence.InheritanceType; -import javax.persistence.Table; - -/** - * A baseline (a.k.a. whitelist) contains a set of expected values for a - * measurement comparison. In the case of a TPM a baseline for that would - * contain the PCR IDs along with the expected hash values. This is similar for - * IMA. - *

- * The Baseline class represents a baseline. This is an abstract - * class for referencing Baselines. A Baseline is - * identified by its name, so the name for a Baseline must be - * unique. - */ -@Entity -@Table(name = "Baseline") -@Inheritance(strategy = InheritanceType.JOINED) -@Access(AccessType.FIELD) -public abstract class Baseline extends UserDefinedEntity { - - @Column(nullable = false, name = "severity") - @Enumerated(EnumType.STRING) - private AlertSeverity severity = AlertSeverity.UNSPECIFIED; - - @Column(nullable = false) - private String type; - - /** - * Creates a new Baseline with the specified name. - * - * @param name name - */ - public Baseline(final String name) { - super(name); - type = getClass().getSimpleName(); - } - - /** - * Default empty constructor is required for Hibernate. It is protected to - * prevent code from calling it directly. - */ - protected Baseline() { - super(); - type = getClass().getSimpleName(); - } - - /** - * When baselines are serialized to be sent to the browser, this can be used - * to determine the type of baseline. - * - * @return The class name for the baseline - */ - public String getType() { - return this.type; - } - - /** - * Gets the baseline severity. - * @return the severity - */ - public AlertSeverity getSeverity() { - return severity; - } - - /** - * Sets the severity of alerts raised by this baseline. - * @param severity The desired severity of alerts raised by this baseline - */ - public void setSeverity(final AlertSeverity severity) { - this.severity = severity; - } -} +package hirs.data.persist.baseline; + +import hirs.data.persist.UserDefinedEntity; +import hirs.data.persist.enums.AlertSeverity; +import javax.persistence.Access; +import javax.persistence.AccessType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; + +/** + * A baseline (a.k.a. whitelist) contains a set of expected values for a + * measurement comparison. In the case of a TPM a baseline for that would + * contain the PCR IDs along with the expected hash values. This is similar for + * IMA. + *

+ * The Baseline class represents a baseline. This is an abstract + * class for referencing Baselines. A Baseline is + * identified by its name, so the name for a Baseline must be + * unique. + */ +@Entity +@Table(name = "Baseline") +@Inheritance(strategy = InheritanceType.JOINED) +@Access(AccessType.FIELD) +public abstract class Baseline extends UserDefinedEntity { + + @Column(nullable = false, name = "severity") + @Enumerated(EnumType.STRING) + private AlertSeverity severity = AlertSeverity.UNSPECIFIED; + + @Column(nullable = false) + private String type; + + /** + * Creates a new Baseline with the specified name. + * + * @param name name + */ + public Baseline(final String name) { + super(name); + type = getClass().getSimpleName(); + } + + /** + * Default empty constructor is required for Hibernate. It is protected to + * prevent code from calling it directly. + */ + protected Baseline() { + super(); + type = getClass().getSimpleName(); + } + + /** + * When baselines are serialized to be sent to the browser, this can be used + * to determine the type of baseline. + * + * @return The class name for the baseline + */ + public String getType() { + return this.type; + } + + /** + * Gets the baseline severity. + * @return the severity + */ + public AlertSeverity getSeverity() { + return severity; + } + + /** + * Sets the severity of alerts raised by this baseline. + * @param severity The desired severity of alerts raised by this baseline + */ + public void setSeverity(final AlertSeverity severity) { + this.severity = severity; + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/baseline/IMABaselineRecord.java b/HIRS_Utils/src/main/java/hirs/data/persist/baseline/IMABaselineRecord.java index a7eac810e..fda5daa3e 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/baseline/IMABaselineRecord.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/baseline/IMABaselineRecord.java @@ -1,176 +1,176 @@ -package hirs.data.persist.baseline; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.Index; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; -import javax.persistence.Transient; - -import com.google.common.base.Preconditions; -import hirs.data.persist.Digest; - -/** - * An IMABaselineRecord represents a single entry in an - * {@link ImaAcceptableRecordBaseline}. These contain paths and hashes of expected - * entries in a machine's IMA log, and are used in the contexts of whitelists and required - * sets via ImaAcceptableRecordBaselines. - */ -@Entity -@Table(indexes = { @Index(columnList = "bucket") }) -public class IMABaselineRecord extends AbstractImaBaselineRecord { - /** - * IMABaselineRecords are randomly assigned buckets based on a hash of their path. These - * bucket values are used to artificially segment the baseline into equal divisions for - * simultaneous multithreaded retrieval. This defines the number of distinct bucket values that - * will be used in this process. - */ - public static final int FILENAME_HASH_BUCKET_COUNT = 4; - - /** - * Holds the name of the 'bucket' field. - */ - public static final String BUCKET_FIELD = "bucket"; - - @Column(name = BUCKET_FIELD, nullable = false) - private final int bucket; - - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "ima_baseline_id") - private SimpleImaBaseline baseline; - - @Transient - private static final Pattern RECORD_PATTERN = Pattern.compile("\\((.*), (.*)\\)"); - - /** - * Creates a new IMABaselineRecord. - * @param path - * file path of the record - * @param hash - * hash of the record - */ - public IMABaselineRecord(final String path, final Digest hash) { - super(path, hash, null); - Preconditions.checkNotNull(path, "Path cannot be null."); - Preconditions.checkNotNull(hash, "Hash cannot be null."); - this.bucket = getBucket(path); - } - - /** - * Creates a new IMABaselineRecord. Creates a new record and - * specifies all of the properties. All of the properties may be null - * except for path and hash. - * - * @param path - * file path - * @param hash - * file SHA-1 hash - * @param baseline - * baseline assigned to the record (nullable) - * @throws IllegalArgumentException - * if digest algorithm is not SHA-1 - */ - public IMABaselineRecord(final String path, final Digest hash, final SimpleImaBaseline baseline) - throws IllegalArgumentException { - this(path, hash); - setBaselineForRecordManager(baseline); - } - - /** - * Returns the 'bucket' of the given path (based on its hash). - * - * @param path the path to hash - * @return the hash of the path - */ - private static int getBucket(final String path) { - if (path == null) { - throw new IllegalArgumentException("Cannot get bucket for null value"); - } - return Math.abs(getPartialPath(path).hashCode()) % FILENAME_HASH_BUCKET_COUNT; - } - - /** - * Default constructor necessary for Hibernate. - */ - protected IMABaselineRecord() { - super(); - this.bucket = 0; - } - - /** - * This gets the baseline. - * - * @return Baseline - */ - public final ImaBaseline getBaseline() { - return baseline; - } - - /** - * Sets the given baseline. - * - * @param baseline baseline that matches the given baseline - */ - public final void setBaseline(final SimpleImaBaseline baseline) { - setOnlyBaseline(baseline); - if (baseline != null) { - baseline.addOnlyToBaseline(this); - } - } - - /** - * Sets the baseline for this record. - * - * @param baseline - * baseline or null - */ - final void setOnlyBaseline(final SimpleImaBaseline baseline) { - if (this.baseline != null && baseline != null) { - this.baseline.removeOnlyBaseline(this); - } - - this.baseline = baseline; - } - - /** - * This method is to be used strictly for when the record is being added or modified by the - * ImaBaselineRecordManager. The methods - * {@link #setBaseline(hirs.data.persist.SimpleImaBaseline)} and {@link - * #setOnlyBaseline(hirs.data.persist.SimpleImaBaseline)} will still need to exist for - * use with the BaselineManager - * - * @param baseline - * SimpleImaBaseline that will be set and persisted by the - * ImaBaselineRecordManager - */ - public final void setBaselineForRecordManager(final SimpleImaBaseline baseline) { - this.baseline = baseline; - } - - /** - * Reverses the toString operation. Throws an IllegalArgumentException if an invalid String is - * passed in - * - * @param record - * String representation of the IMABaselineRecord - * @return IMABaselineRecord - */ - public static IMABaselineRecord fromString(final String record) { - Matcher m = RECORD_PATTERN.matcher(record); - m.matches(); - if (m.groupCount() != 2) { - String msg = String.format("Unexpected number of groups found with pattern \"%s\" " - + "on string \"%s\"", RECORD_PATTERN.toString(), record); - throw new IllegalArgumentException(msg); - } - String path = m.group(1); - String digestString = m.group(2); - Digest digest = Digest.fromString(digestString); - return new IMABaselineRecord(path, digest); - } -} +package hirs.data.persist.baseline; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Index; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.google.common.base.Preconditions; +import hirs.data.persist.Digest; + +/** + * An IMABaselineRecord represents a single entry in an + * {@link ImaAcceptableRecordBaseline}. These contain paths and hashes of expected + * entries in a machine's IMA log, and are used in the contexts of whitelists and required + * sets via ImaAcceptableRecordBaselines. + */ +@Entity +@Table(indexes = { @Index(columnList = "bucket") }) +public class IMABaselineRecord extends AbstractImaBaselineRecord { + /** + * IMABaselineRecords are randomly assigned buckets based on a hash of their path. These + * bucket values are used to artificially segment the baseline into equal divisions for + * simultaneous multithreaded retrieval. This defines the number of distinct bucket values that + * will be used in this process. + */ + public static final int FILENAME_HASH_BUCKET_COUNT = 4; + + /** + * Holds the name of the 'bucket' field. + */ + public static final String BUCKET_FIELD = "bucket"; + + @Column(name = BUCKET_FIELD, nullable = false) + private final int bucket; + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "ima_baseline_id") + private SimpleImaBaseline baseline; + + @Transient + private static final Pattern RECORD_PATTERN = Pattern.compile("\\((.*), (.*)\\)"); + + /** + * Creates a new IMABaselineRecord. + * @param path + * file path of the record + * @param hash + * hash of the record + */ + public IMABaselineRecord(final String path, final Digest hash) { + super(path, hash, null); + Preconditions.checkNotNull(path, "Path cannot be null."); + Preconditions.checkNotNull(hash, "Hash cannot be null."); + this.bucket = getBucket(path); + } + + /** + * Creates a new IMABaselineRecord. Creates a new record and + * specifies all of the properties. All of the properties may be null + * except for path and hash. + * + * @param path + * file path + * @param hash + * file SHA-1 hash + * @param baseline + * baseline assigned to the record (nullable) + * @throws IllegalArgumentException + * if digest algorithm is not SHA-1 + */ + public IMABaselineRecord(final String path, final Digest hash, final SimpleImaBaseline baseline) + throws IllegalArgumentException { + this(path, hash); + setBaselineForRecordManager(baseline); + } + + /** + * Returns the 'bucket' of the given path (based on its hash). + * + * @param path the path to hash + * @return the hash of the path + */ + private static int getBucket(final String path) { + if (path == null) { + throw new IllegalArgumentException("Cannot get bucket for null value"); + } + return Math.abs(getPartialPath(path).hashCode()) % FILENAME_HASH_BUCKET_COUNT; + } + + /** + * Default constructor necessary for Hibernate. + */ + protected IMABaselineRecord() { + super(); + this.bucket = 0; + } + + /** + * This gets the baseline. + * + * @return Baseline + */ + public final ImaBaseline getBaseline() { + return baseline; + } + + /** + * Sets the given baseline. + * + * @param baseline baseline that matches the given baseline + */ + public final void setBaseline(final SimpleImaBaseline baseline) { + setOnlyBaseline(baseline); + if (baseline != null) { + baseline.addOnlyToBaseline(this); + } + } + + /** + * Sets the baseline for this record. + * + * @param baseline + * baseline or null + */ + final void setOnlyBaseline(final SimpleImaBaseline baseline) { + if (this.baseline != null && baseline != null) { + this.baseline.removeOnlyBaseline(this); + } + + this.baseline = baseline; + } + + /** + * This method is to be used strictly for when the record is being added or modified by the + * ImaBaselineRecordManager. The methods + * {@link #setBaseline(hirs.data.persist.SimpleImaBaseline)} and {@link + * #setOnlyBaseline(hirs.data.persist.SimpleImaBaseline)} will still need to exist for + * use with the BaselineManager + * + * @param baseline + * SimpleImaBaseline that will be set and persisted by the + * ImaBaselineRecordManager + */ + public final void setBaselineForRecordManager(final SimpleImaBaseline baseline) { + this.baseline = baseline; + } + + /** + * Reverses the toString operation. Throws an IllegalArgumentException if an invalid String is + * passed in + * + * @param record + * String representation of the IMABaselineRecord + * @return IMABaselineRecord + */ + public static IMABaselineRecord fromString(final String record) { + Matcher m = RECORD_PATTERN.matcher(record); + m.matches(); + if (m.groupCount() != 2) { + String msg = String.format("Unexpected number of groups found with pattern \"%s\" " + + "on string \"%s\"", RECORD_PATTERN.toString(), record); + throw new IllegalArgumentException(msg); + } + String path = m.group(1); + String digestString = m.group(2); + Digest digest = Digest.fromString(digestString); + return new IMABaselineRecord(path, digest); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/baseline/ImaBaseline.java b/HIRS_Utils/src/main/java/hirs/data/persist/baseline/ImaBaseline.java index 809b2a2c8..d91232014 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/baseline/ImaBaseline.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/baseline/ImaBaseline.java @@ -1,114 +1,114 @@ -package hirs.data.persist.baseline; - -import hirs.data.persist.IMAMeasurementRecord; -import hirs.data.persist.IMAPolicy; -import hirs.ima.matching.BatchImaMatchStatus; -import hirs.persist.ImaBaselineRecordManager; -import org.hibernate.annotations.Type; - -import javax.persistence.Access; -import javax.persistence.AccessType; -import javax.persistence.Column; -import javax.persistence.Entity; -import java.util.Collection; -import java.util.Date; - -/** - * Class represents the basic functionality of an IMA baseline: determining whether a baseline - * 'contains' {@link IMAMeasurementRecord}s that were collected from a machine's IMA log. - * Extending classes represent different ways to assemble and manipulate these baselines. See - * {@link SimpleImaBaseline} for an example of a baseline with records that can be manually - * added and removed. - * - * @param the type of record that this baseline holds - */ -@Entity -@Access(AccessType.FIELD) -public abstract class ImaBaseline extends Baseline { - @Column - @Type(type = "timestamp") - private Date date; - - /** - * Creates a new ImaBaseline with the given name. - * - * @param name a name used to uniquely identify and reference the IMA baseline - */ - public ImaBaseline(final String name) { - super(name); - date = new Date(); - } - - /** - * Default constructor necessary for Hibernate. - */ - protected ImaBaseline() { - super(); - date = new Date(); - } - - /** - * Tests whether the record is found in the baseline. This returns a - * ReportMatchStatus representing the result of the search for - * the record. The returns conditions are as follows: - *

- *

- * If partial paths are enabled, records not starting with '/' are compared - * against all baseline records not starting with '/' and the last segment - * (the filename after the last '/') of each full path baseline record. - * Records starting with '/' are compared against all full path baseline - * records and the last segment of the record is compared against all - * partial path baseline records. - *

- * If partial paths are disabled, records are only compared using the full - * path of the baseline record and the report record. - * - * @param records - * measurement records to find in this baseline - * @param recordManager - * an ImaBaselineRecordManager that can be used to retrieve persisted records - * @param imaPolicy - * the IMA policy to use while determining if a baseline contains the given records - * - * @return batch match status for the measurement records - */ - public abstract BatchImaMatchStatus contains( - Collection records, - ImaBaselineRecordManager recordManager, - IMAPolicy imaPolicy - ); - - /** - * Set this IMABaselines's date, which can either - * be the date that it was added, or some other date such as the patch date - * this baseline is associated with. - * - * @param newDate - * the new date to set, can be null - */ - public final void setDate(final Date newDate) { - if (newDate == null) { - this.date = null; - } else { - this.date = new Date(newDate.getTime()); - } - } - - /** - * Get this IMABaselines's date, which can either - * be the date that it was added, or some other date such as the patch date - * this baseline is associated with. - * - * @return this baseline's date, can be null - */ - public final Date getDate() { - return new Date(date.getTime()); - } -} +package hirs.data.persist.baseline; + +import hirs.data.persist.IMAMeasurementRecord; +import hirs.data.persist.IMAPolicy; +import hirs.ima.matching.BatchImaMatchStatus; +import hirs.persist.ImaBaselineRecordManager; +import org.hibernate.annotations.Type; + +import javax.persistence.Access; +import javax.persistence.AccessType; +import javax.persistence.Column; +import javax.persistence.Entity; +import java.util.Collection; +import java.util.Date; + +/** + * Class represents the basic functionality of an IMA baseline: determining whether a baseline + * 'contains' {@link IMAMeasurementRecord}s that were collected from a machine's IMA log. + * Extending classes represent different ways to assemble and manipulate these baselines. See + * {@link SimpleImaBaseline} for an example of a baseline with records that can be manually + * added and removed. + * + * @param the type of record that this baseline holds + */ +@Entity +@Access(AccessType.FIELD) +public abstract class ImaBaseline extends Baseline { + @Column + @Type(type = "timestamp") + private Date date; + + /** + * Creates a new ImaBaseline with the given name. + * + * @param name a name used to uniquely identify and reference the IMA baseline + */ + public ImaBaseline(final String name) { + super(name); + date = new Date(); + } + + /** + * Default constructor necessary for Hibernate. + */ + protected ImaBaseline() { + super(); + date = new Date(); + } + + /** + * Tests whether the record is found in the baseline. This returns a + * ReportMatchStatus representing the result of the search for + * the record. The returns conditions are as follows: + *

+ *

+ * If partial paths are enabled, records not starting with '/' are compared + * against all baseline records not starting with '/' and the last segment + * (the filename after the last '/') of each full path baseline record. + * Records starting with '/' are compared against all full path baseline + * records and the last segment of the record is compared against all + * partial path baseline records. + *

+ * If partial paths are disabled, records are only compared using the full + * path of the baseline record and the report record. + * + * @param records + * measurement records to find in this baseline + * @param recordManager + * an ImaBaselineRecordManager that can be used to retrieve persisted records + * @param imaPolicy + * the IMA policy to use while determining if a baseline contains the given records + * + * @return batch match status for the measurement records + */ + public abstract BatchImaMatchStatus contains( + Collection records, + ImaBaselineRecordManager recordManager, + IMAPolicy imaPolicy + ); + + /** + * Set this IMABaselines's date, which can either + * be the date that it was added, or some other date such as the patch date + * this baseline is associated with. + * + * @param newDate + * the new date to set, can be null + */ + public final void setDate(final Date newDate) { + if (newDate == null) { + this.date = null; + } else { + this.date = new Date(newDate.getTime()); + } + } + + /** + * Get this IMABaselines's date, which can either + * be the date that it was added, or some other date such as the patch date + * this baseline is associated with. + * + * @return this baseline's date, can be null + */ + public final Date getDate() { + return new Date(date.getTime()); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java b/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java index df41bb082..7c80dc830 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/certificate/Certificate.java @@ -14,9 +14,9 @@ import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.ASN1TaggedObject; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DEROctetString; -import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DLSequence; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.AccessDescription; @@ -36,7 +36,6 @@ import org.bouncycastle.cert.X509AttributeCertificateHolder; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.util.encoders.Base64; -import org.bouncycastle.x509.extension.X509ExtensionUtil; import javax.persistence.Column; import javax.persistence.Entity; @@ -557,7 +556,7 @@ protected CertificateType getCertificateType() throws IOException { // V1 X509Certificate return CertificateType.X509_CERTIFICATE; } - } else if (testSeq.toArray()[0] instanceof DERTaggedObject) { + } else if (testSeq.toArray()[0] instanceof ASN1TaggedObject) { // V2 or V3 X509Certificate return CertificateType.X509_CERTIFICATE; } @@ -678,13 +677,16 @@ private ASN1Primitive getExtensionValue(final String oid) throws IOException { * * @return List Authority info access list */ - private String getAuthorityInfoAccess(final byte[] authoInfoAccess) { + @SuppressWarnings("deprecation") +private String getAuthorityInfoAccess(final byte[] authoInfoAccess) { StringBuilder sb = new StringBuilder(); try { if (authoInfoAccess != null && authoInfoAccess.length > 0) { sb.append(getAuthorityInfoAccess(AuthorityInformationAccess - .getInstance(X509ExtensionUtil.fromExtensionValue(authoInfoAccess)))); + .getInstance( + org.bouncycastle.x509.extension.X509ExtensionUtil.fromExtensionValue( + authoInfoAccess)))); } } catch (IOException ioEx) { LOGGER.error(ioEx); diff --git a/HIRS_Utils/src/main/java/hirs/data/persist/certificate/EndorsementCredential.java b/HIRS_Utils/src/main/java/hirs/data/persist/certificate/EndorsementCredential.java index 820439ab1..e4a1b9052 100644 --- a/HIRS_Utils/src/main/java/hirs/data/persist/certificate/EndorsementCredential.java +++ b/HIRS_Utils/src/main/java/hirs/data/persist/certificate/EndorsementCredential.java @@ -31,7 +31,6 @@ import org.bouncycastle.asn1.DERNumericString; import org.bouncycastle.asn1.DERPrintableString; import org.bouncycastle.asn1.DERT61String; -import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.DERUniversalString; import org.bouncycastle.asn1.DERVisibleString; @@ -419,10 +418,10 @@ private void parseSequence(final ASN1Sequence seq, final boolean addToMapping, LOGGER.debug("Found TPM Assertions: " + tpmSecurityAssertions.toString()); // Iterate through remaining fields to set optional attributes int tag; - DERTaggedObject obj; + ASN1TaggedObject obj; for (int i = seqPosition; i < seq.size(); i++) { - if (seq.getObjectAt(i) instanceof DERTaggedObject) { - obj = (DERTaggedObject) seq.getObjectAt(i); + if (seq.getObjectAt(i) instanceof ASN1TaggedObject) { + obj = (ASN1TaggedObject) seq.getObjectAt(i); tag = obj.getTagNo(); if (tag == EK_TYPE_TAG) { int ekGenTypeVal = ((ASN1Enumerated) obj.getObject()).getValue().intValue(); diff --git a/HIRS_Utils/src/main/java/hirs/ima/IMABaselineGeneratorException.java b/HIRS_Utils/src/main/java/hirs/ima/IMABaselineGeneratorException.java index 8fbf45f3b..08aae06ba 100644 --- a/HIRS_Utils/src/main/java/hirs/ima/IMABaselineGeneratorException.java +++ b/HIRS_Utils/src/main/java/hirs/ima/IMABaselineGeneratorException.java @@ -1,46 +1,46 @@ -package hirs.ima; - -/** - * This class represents an Exception generated by a - * CreateIMABaseline. - */ -public class IMABaselineGeneratorException extends Exception { - - private static final long serialVersionUID = 1704308568386321875L; - - /** - * Creates a new CreateIMABaselineException that has the - * message msg. - * - * @param msg - * exception message - */ - IMABaselineGeneratorException(final String msg) { - super(msg); - } - - /** - * Creates a new CreateIMABaselineException that wraps the - * given Throwable. - * - * @param t - * root cause - */ - IMABaselineGeneratorException(final Throwable t) { - super(t); - } - - /** - * Creates a new CreateIMABaselineException that has the - * message msg and wraps the root cause. - * - * @param msg - * exception message - * @param t - * root cause - */ - IMABaselineGeneratorException(final String msg, final Throwable t) { - super(msg, t); - } - -} +package hirs.ima; + +/** + * This class represents an Exception generated by a + * CreateIMABaseline. + */ +public class IMABaselineGeneratorException extends Exception { + + private static final long serialVersionUID = 1704308568386321875L; + + /** + * Creates a new CreateIMABaselineException that has the + * message msg. + * + * @param msg + * exception message + */ + IMABaselineGeneratorException(final String msg) { + super(msg); + } + + /** + * Creates a new CreateIMABaselineException that wraps the + * given Throwable. + * + * @param t + * root cause + */ + IMABaselineGeneratorException(final Throwable t) { + super(t); + } + + /** + * Creates a new CreateIMABaselineException that has the + * message msg and wraps the root cause. + * + * @param msg + * exception message + * @param t + * root cause + */ + IMABaselineGeneratorException(final String msg, final Throwable t) { + super(msg, t); + } + +} diff --git a/HIRS_Utils/src/main/java/hirs/package-info.java b/HIRS_Utils/src/main/java/hirs/package-info.java index a2804c076..8133e728d 100755 --- a/HIRS_Utils/src/main/java/hirs/package-info.java +++ b/HIRS_Utils/src/main/java/hirs/package-info.java @@ -1,7 +1,7 @@ -/** - * Package contains objects used to manage the exchange of request - * response objects that are passed between the HIRS Client and HIRS - * Appraiser components. - */ -package hirs; - +/** + * Package contains objects used to manage the exchange of request + * response objects that are passed between the HIRS Client and HIRS + * Appraiser components. + */ +package hirs; + diff --git a/HIRS_Utils/src/main/java/hirs/persist/BaselineManager.java b/HIRS_Utils/src/main/java/hirs/persist/BaselineManager.java index 7951a8348..fcf92e3bc 100644 --- a/HIRS_Utils/src/main/java/hirs/persist/BaselineManager.java +++ b/HIRS_Utils/src/main/java/hirs/persist/BaselineManager.java @@ -1,231 +1,231 @@ -package hirs.persist; - -import hirs.FilteredRecordsList; -import hirs.data.bean.SimpleBaselineBean; -import hirs.data.persist.baseline.Baseline; -import hirs.data.persist.baseline.IMABaselineRecord; -import hirs.data.persist.ImaBlacklistRecord; -import hirs.repository.RepoPackage; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * A BaselineManager manages Baselines. A BaselineManager can - * read, update, and archive Baselines. - */ -public interface BaselineManager extends OrderedListQuerier { - - /** - * Stores a new Baseline. This stores a new - * Baseline to be managed by the BaselineManager. - * If the Baseline is successfully saved then a reference to it - * is returned. - * - * @param baseline baseline to save - * @return reference to saved baseline - * @throws BaselineManagerException if baseline is already saved or other error occurs - */ - Baseline saveBaseline(Baseline baseline) throws BaselineManagerException; - - /** - * Updates a Baseline. This updates the Baseline - * that is managed so subsequent calls to get this Baseline - * will return the values set by the incoming Baseline. - * - * @param baseline baseline - * @throws BaselineManagerException if unable to update the baseline - */ - void updateBaseline(Baseline baseline) throws BaselineManagerException; - - /** - * Returns a list of all baseline names managed by this manager. Every - * Baseline must have a name that users can use to reference - * the Baseline. This returns a listing of all the - * Baselines. - *

- * A Class argument may be specified to limit which types of - * Baselines to return. This argument may be null to return all - * Baselines. - * - * @param clazz - * class type of Baselines to return (may be null) - * @return list of Baseline names - * @throws BaselineManagerException if unable to create the list - */ - List getBaselineList(Class clazz) - throws BaselineManagerException; - - /** - * Returns a list of all Baselines that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. The returned list does not - * contain Baselines that have been soft-deleted. - * - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @param searchableColumns Map of String and boolean values with column - * headers and whether they are to. Boolean is true if field provides - * a typical String that can be searched by Hibernate without - * transformation. - * @return FilteredRecordsList object with fields for DataTables - * @throws BaselineManagerException if unable to create the list - */ - FilteredRecordsList getOrderedBaselineList( - String columnToOrder, boolean ascending, - int firstResult, int maxResults, String search, - Map searchableColumns) - throws BaselineManagerException; - - /** - * Returns a list of all ImaBaseline Records that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. - * - * @param baselineId id of the baseline - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @return FilteredRecordsList object with fields for DataTables - * @throws BaselineManagerException if unable to create the list - */ - FilteredRecordsList getOrderedRecordList( - UUID baselineId, String columnToOrder, boolean ascending, - int firstResult, int maxResults, String search) - throws BaselineManagerException; - - /** - * Returns a list of all ImaBlacklistBaseline Records that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. - * - * @param baselineId id of the baseline - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @return FilteredRecordsList object with fields for DataTables - * @throws BaselineManagerException if unable to create the list - */ - FilteredRecordsList getOrderedBlacklistRecordList( - UUID baselineId, String columnToOrder, boolean ascending, - int firstResult, int maxResults, String search) - throws BaselineManagerException; - - /** - * Returns a list of all RepoPackages that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. - * - * @param name name of the baseline - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @return FilteredRecordsList object with fields for DataTables - * @throws BaselineManagerException if unable to create the list - */ - FilteredRecordsList getOrderedPackageList( - String name, String columnToOrder, boolean ascending, - int firstResult, int maxResults, String search) - throws BaselineManagerException; - - /** - * Returns a list of all IMABaselineRecords in the specified package. - * - * @param id of the package - * @param search string of criteria to be matched to visible columns - * @return List the records - * @throws BaselineManagerException if unable to create the list - */ - List getPackageRecords( - UUID id, String search) throws BaselineManagerException; - - /** - * Retrieves the Baseline identified by name. If - * the Baseline cannot be found then null is returned. - * - * @param name name of the Baseline - * @return Baseline whose name is name or null if not found - * @throws BaselineManagerException if unable to retrieve the baseline - */ - Baseline getBaseline(String name) throws BaselineManagerException; - - /** - * Retrieves the Baseline identified by the given id. If - * the Baseline cannot be found then null is returned. - * - * @param id the id of the desired Baseline - * @return Baseline whose id is id or null if not found - * @throws BaselineManagerException if unable to retrieve the baseline - */ - Baseline getBaseline(Serializable id) throws BaselineManagerException; - - /** - * Retrieves the Baseline identified by name. This method - * fully loads a Baseline object; any lazy fields will be recursively loaded. This is - * necessary when conducting an appraisal. If the Baseline cannot be found - * then null is returned. - * - * @param name name of the Baseline - * @return Baseline whose name is name or null if not found - * @throws BaselineManagerException if unable to retrieve the baseline - */ - Baseline getCompleteBaseline(String name) throws BaselineManagerException; - - /** - * Archives the named {@link Baseline} and updates it in the database. - * - * @param name name of the {@link Baseline} to archive - * @return true if the {@link Baseline} was successfully found and archived, false if the - * {@link Baseline} was not found - * @throws DBManagerException - * if the {@link Baseline} is not an instance of ArchivableEntity. - */ - boolean archive(String name) throws DBManagerException; - - /** - * Deletes the named {@link Baseline} from the database. - * - * @param baseline {@link Baseline} to be deleted - * @return true if the {@link Baseline} was successfully found and - * deleted, false if the {@link Baseline} was not found - * @throws DBManagerException - * if the {@link Baseline} is not an instance of ArchivableEntity. - */ - boolean delete(Baseline baseline) throws DBManagerException; - - /** - * Returns a list of all Baselines that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. The returned list does not - * contain Baselines that have been soft-deleted. The records stored within each - * baseline are not loaded. - * - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @param searchableColumns Map of String and boolean values with column - * headers and whether they are to. Boolean is true if field provides - * a typical String that can be searched by Hibernate without - * transformation. - * @return FilteredRecordsList object with fields for DataTables - * @throws BaselineManagerException if unable to create the list - */ - FilteredRecordsList getOrderedBaselineListWithoutRecords( - String columnToOrder, boolean ascending, - int firstResult, int maxResults, String search, - Map searchableColumns) - throws BaselineManagerException; -} +package hirs.persist; + +import hirs.FilteredRecordsList; +import hirs.data.bean.SimpleBaselineBean; +import hirs.data.persist.baseline.Baseline; +import hirs.data.persist.baseline.IMABaselineRecord; +import hirs.data.persist.ImaBlacklistRecord; +import hirs.repository.RepoPackage; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * A BaselineManager manages Baselines. A BaselineManager can + * read, update, and archive Baselines. + */ +public interface BaselineManager extends OrderedListQuerier { + + /** + * Stores a new Baseline. This stores a new + * Baseline to be managed by the BaselineManager. + * If the Baseline is successfully saved then a reference to it + * is returned. + * + * @param baseline baseline to save + * @return reference to saved baseline + * @throws BaselineManagerException if baseline is already saved or other error occurs + */ + Baseline saveBaseline(Baseline baseline) throws BaselineManagerException; + + /** + * Updates a Baseline. This updates the Baseline + * that is managed so subsequent calls to get this Baseline + * will return the values set by the incoming Baseline. + * + * @param baseline baseline + * @throws BaselineManagerException if unable to update the baseline + */ + void updateBaseline(Baseline baseline) throws BaselineManagerException; + + /** + * Returns a list of all baseline names managed by this manager. Every + * Baseline must have a name that users can use to reference + * the Baseline. This returns a listing of all the + * Baselines. + *

+ * A Class argument may be specified to limit which types of + * Baselines to return. This argument may be null to return all + * Baselines. + * + * @param clazz + * class type of Baselines to return (may be null) + * @return list of Baseline names + * @throws BaselineManagerException if unable to create the list + */ + List getBaselineList(Class clazz) + throws BaselineManagerException; + + /** + * Returns a list of all Baselines that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. The returned list does not + * contain Baselines that have been soft-deleted. + * + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @param searchableColumns Map of String and boolean values with column + * headers and whether they are to. Boolean is true if field provides + * a typical String that can be searched by Hibernate without + * transformation. + * @return FilteredRecordsList object with fields for DataTables + * @throws BaselineManagerException if unable to create the list + */ + FilteredRecordsList getOrderedBaselineList( + String columnToOrder, boolean ascending, + int firstResult, int maxResults, String search, + Map searchableColumns) + throws BaselineManagerException; + + /** + * Returns a list of all ImaBaseline Records that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. + * + * @param baselineId id of the baseline + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @return FilteredRecordsList object with fields for DataTables + * @throws BaselineManagerException if unable to create the list + */ + FilteredRecordsList getOrderedRecordList( + UUID baselineId, String columnToOrder, boolean ascending, + int firstResult, int maxResults, String search) + throws BaselineManagerException; + + /** + * Returns a list of all ImaBlacklistBaseline Records that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. + * + * @param baselineId id of the baseline + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @return FilteredRecordsList object with fields for DataTables + * @throws BaselineManagerException if unable to create the list + */ + FilteredRecordsList getOrderedBlacklistRecordList( + UUID baselineId, String columnToOrder, boolean ascending, + int firstResult, int maxResults, String search) + throws BaselineManagerException; + + /** + * Returns a list of all RepoPackages that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. + * + * @param name name of the baseline + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @return FilteredRecordsList object with fields for DataTables + * @throws BaselineManagerException if unable to create the list + */ + FilteredRecordsList getOrderedPackageList( + String name, String columnToOrder, boolean ascending, + int firstResult, int maxResults, String search) + throws BaselineManagerException; + + /** + * Returns a list of all IMABaselineRecords in the specified package. + * + * @param id of the package + * @param search string of criteria to be matched to visible columns + * @return List the records + * @throws BaselineManagerException if unable to create the list + */ + List getPackageRecords( + UUID id, String search) throws BaselineManagerException; + + /** + * Retrieves the Baseline identified by name. If + * the Baseline cannot be found then null is returned. + * + * @param name name of the Baseline + * @return Baseline whose name is name or null if not found + * @throws BaselineManagerException if unable to retrieve the baseline + */ + Baseline getBaseline(String name) throws BaselineManagerException; + + /** + * Retrieves the Baseline identified by the given id. If + * the Baseline cannot be found then null is returned. + * + * @param id the id of the desired Baseline + * @return Baseline whose id is id or null if not found + * @throws BaselineManagerException if unable to retrieve the baseline + */ + Baseline getBaseline(Serializable id) throws BaselineManagerException; + + /** + * Retrieves the Baseline identified by name. This method + * fully loads a Baseline object; any lazy fields will be recursively loaded. This is + * necessary when conducting an appraisal. If the Baseline cannot be found + * then null is returned. + * + * @param name name of the Baseline + * @return Baseline whose name is name or null if not found + * @throws BaselineManagerException if unable to retrieve the baseline + */ + Baseline getCompleteBaseline(String name) throws BaselineManagerException; + + /** + * Archives the named {@link Baseline} and updates it in the database. + * + * @param name name of the {@link Baseline} to archive + * @return true if the {@link Baseline} was successfully found and archived, false if the + * {@link Baseline} was not found + * @throws DBManagerException + * if the {@link Baseline} is not an instance of ArchivableEntity. + */ + boolean archive(String name) throws DBManagerException; + + /** + * Deletes the named {@link Baseline} from the database. + * + * @param baseline {@link Baseline} to be deleted + * @return true if the {@link Baseline} was successfully found and + * deleted, false if the {@link Baseline} was not found + * @throws DBManagerException + * if the {@link Baseline} is not an instance of ArchivableEntity. + */ + boolean delete(Baseline baseline) throws DBManagerException; + + /** + * Returns a list of all Baselines that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. The returned list does not + * contain Baselines that have been soft-deleted. The records stored within each + * baseline are not loaded. + * + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @param searchableColumns Map of String and boolean values with column + * headers and whether they are to. Boolean is true if field provides + * a typical String that can be searched by Hibernate without + * transformation. + * @return FilteredRecordsList object with fields for DataTables + * @throws BaselineManagerException if unable to create the list + */ + FilteredRecordsList getOrderedBaselineListWithoutRecords( + String columnToOrder, boolean ascending, + int firstResult, int maxResults, String search, + Map searchableColumns) + throws BaselineManagerException; +} diff --git a/HIRS_Utils/src/main/java/hirs/persist/DBReportManager.java b/HIRS_Utils/src/main/java/hirs/persist/DBReportManager.java index 7f048c251..d578a655e 100755 --- a/HIRS_Utils/src/main/java/hirs/persist/DBReportManager.java +++ b/HIRS_Utils/src/main/java/hirs/persist/DBReportManager.java @@ -1,635 +1,635 @@ -package hirs.persist; - -import hirs.FilteredRecordsList; -import hirs.data.bean.SimpleImaRecordBean; -import hirs.data.persist.IMAMeasurementRecord; -import hirs.data.persist.IMAReport; -import hirs.data.persist.IntegrityReport; -import hirs.data.persist.Report; -import hirs.data.persist.ReportSummary; -import hirs.persist.imarecord.DbImaRecordQueryForDevice; -import hirs.persist.imarecord.DbImaRecordQueryForDeviceSinceLastFullReport; -import hirs.persist.imarecord.DbImaRecordQueryForNone; -import hirs.persist.imarecord.DbImaRecordQueryForReport; -import hirs.persist.imarecord.DbImaRecordQueryParameters; -import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; -import org.hibernate.Criteria; -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.criterion.Conjunction; -import org.hibernate.criterion.Disjunction; -import org.hibernate.criterion.MatchMode; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.hibernate.transform.Transformers; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import static org.apache.logging.log4j.LogManager.getLogger; -import static org.hibernate.criterion.Restrictions.ilike; - -/** - * This class defines a ReportManager that stores the reports in a - * database. - */ -public class DBReportManager extends DBManager implements ReportManager { - private static final Logger LOGGER = getLogger(DBReportManager.class); - - /** - * Creates a new DBReportManager that uses the provided sessionFactory - * to interact with a database. - * - * @param sessionFactory session factory used to access database connections - */ - public DBReportManager(final SessionFactory sessionFactory) { - super(Report.class, sessionFactory); - } - - /** - * Saves the Report in the database and returns it. - * - * @param report - * report to save - * @return Report that was saved - * @throws DBManagerException - * if Report has previously been saved or an error occurs while - * trying to save it to the database - */ - @Override - public final Report saveReport(final Report report) - throws DBManagerException { - LOGGER.debug("Saving report: {}", report); - try { - return super.save(report); - } catch (DBManagerException e) { - throw new ReportManagerException(e); - } - } - - /** - * Returns a list of all Reports of type clazz. - * This searches through the database for this information. - * - * All Reports will be returned without measurement records as they are - * lazily loaded for performance. If the records of a report are necessary, - * a method will need to be written to return the records inside of a - * transaction. - * - * @param clazz - * class type of Reports to return (may be null) - * @return list of Reports - * @throws ReportManagerException - * if unable to search the database - */ - @Override - public final List getReportList(final Class clazz) - throws ReportManagerException { - LOGGER.debug("getting report list"); - try { - return super.getList(clazz); - } catch (DBManagerException e) { - throw new ReportManagerException(e); - } - } - - /** - * Returns a list of all Report Records that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This - * method contains database interactions designed to extract specific - * fields from the database to avoid retrieving full records in order - * to improve query performance and reduce the size of teh data set - * returned to the caller. This method helps support the server-side - * processing in the JQuery DataTables. - * - * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE - * @param id the id or name of the REPORT or DEVICE to search - * @param sinceLastFullReport limits the records to those since the last full report for the - * device - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @param searchableColumns map containing columns that search string can - * be applied to - * @return FilteredRecordsList object with fields for DataTables - * @throws ReportManagerException if unable to create the list - */ - @Override - @SuppressWarnings("checkstyle:parameternumber") - public final FilteredRecordsList - getOrderedRecordListWithoutRecords( - final IMARecordScope scope, - final String id, - final boolean sinceLastFullReport, - final IMARecordField columnToOrder, - final boolean ascending, - final int firstResult, - final int maxResults, - final String search, - final Map searchableColumns) - throws ReportManagerException { - - // check columnToOrder - if (columnToOrder == null) { - final String msg = "columnToOrder cannot be null"; - LOGGER.error(msg); - throw new IllegalArgumentException(msg); - } - - // check scope - if (scope == null) { - throw new IllegalArgumentException("IMARecordScope cannot be null"); - } - - switch (scope) { - case NONE: - // Returns an empty FilteredRecordsList to make DataTables - // display "No Data". - return new FilteredRecordsList<>(); - case REPORT: - return getImaRecordsForReport(id, columnToOrder, ascending, - firstResult, - maxResults, search, searchableColumns); - case DEVICE: - return getImaRecordsForDevice(id, sinceLastFullReport, - columnToOrder, ascending, firstResult, - maxResults, search, searchableColumns); - default: - throw new UnsupportedOperationException( - "IMARecordScope " + scope + " is not supported"); - } - } - - /** - * Returns a list of all Report Records that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. - * - * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE - * @param id the id or name of the REPORT or DEVICE to search - * @param sinceLastFullReport limits the records to those since the last full report for the - * device - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @return FilteredRecordsList object with fields for DataTables - * @throws ReportManagerException if unable to create the list - */ - @Override - @SuppressWarnings("checkstyle:parameternumber") - public final FilteredRecordsList getOrderedRecordList( - final IMARecordScope scope, - final String id, - final boolean sinceLastFullReport, - final IMARecordField columnToOrder, - final boolean ascending, - final int firstResult, - final int maxResults, - final String search) - throws ReportManagerException { - - // check columnToOrder - if (columnToOrder == null) { - final String msg = "columnToOrder cannot be null"; - LOGGER.error(msg); - throw new IllegalArgumentException(msg); - } - - // check scope - if (scope == null) { - throw new IllegalArgumentException("IMARecordScope cannot be null"); - } - - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - try { - tx = session.beginTransaction(); - - final DbImaRecordQueryParameters params - = new DbImaRecordQueryParameters(id, columnToOrder, ascending, - firstResult, maxResults, search); - - switch (scope) { - case NONE: - return new DbImaRecordQueryForNone().query(); - case REPORT: - return new DbImaRecordQueryForReport(session, params).query(); - case DEVICE: - if (sinceLastFullReport) { - DbImaRecordQueryForDeviceSinceLastFullReport q - = new DbImaRecordQueryForDeviceSinceLastFullReport(session, params); - return q.query(); - } else { - return new DbImaRecordQueryForDevice(session, params).query(); - } - default: - throw new UnsupportedOperationException( - "IMARecordScope " + scope + " is not supported"); - } - - } catch (Exception ex) { - String msg = "Error executing IMA Record query for " + scope + " scope."; - if (scope == IMARecordScope.DEVICE) { - msg += "Since last full report = " + sinceLastFullReport; - } - LOGGER.error(msg, ex); - throw ex; - } finally { - if (tx != null) { - tx.rollback(); - } - } - - } - - /** - * Retrieves the Report from the database. This searches the - * database for an entry whose id matches id. It then - * reconstructs a Report object from the database entry. - * - * Note: IMAMeasurementRecords are lazily loaded so the object - * returned will not contain them for performance purposes. If the whole - * report needs to be retrieved a method will need to be written to return - * the records inside of a transaction. - * - * @param id id of the report - * @return report - * @throws ReportManagerException - * if unable to search the database or recreate the Report - */ - @Override - public final Report getReport(final UUID id) throws ReportManagerException { - LOGGER.debug("getting report: {}", id); - try { - return super.get(id); - } catch (DBManagerException e) { - throw new ReportManagerException(e); - } - } - - @Override - public final Report getCompleteReport(final UUID id) throws ReportManagerException { - LOGGER.debug("getting full report: {}", id); - try { - return super.getAndLoadLazyFields(id, true); - } catch (DBManagerException e) { - throw new ReportManagerException(e); - } - } - - /** - * Updates a Report. This updates the database entries - * to reflect the new values that should be set. - * - * @param report - * report to be updated - * @throws ReportManagerException - * if Report an error occurs while updating the report or - * while trying to save it to the database - */ - @Override - public void updateReport(final Report report) throws ReportManagerException { - LOGGER.debug("updating report: {}", report); - try { - super.update(report); - } catch (DBManagerException e) { - throw new ReportManagerException(e); - } - } - - /** - * Deletes the Report from the database. This removes all of - * the database entries that stored information with regards to the this - * Report. - *

- * If the Report is referenced by any other tables then this - * will throw a ReportManagerException. - * - * @param id - * id of the Report to delete - * @return true if successfully found and deleted the Report - * @throws ReportManagerException - * if unable to find the baseline or delete it from the - * database - */ - @Override - public final boolean deleteReport(final UUID id) - throws ReportManagerException { - LOGGER.debug("deleting baseline: {}", id); - try { - return super.delete(id); - } catch (DBManagerException e) { - throw new ReportManagerException(e); - } - } - - private FilteredRecordsList - getImaRecordsForReport( - final String id, - final IMARecordField columnToOrder, - final boolean ascending, - final int firstResult, - final int maxResults, - final String search, - final Map searchableColumns) { - IntegrityReport report = (IntegrityReport) - getReport(UUID.fromString(id)); - IMAReport imaReport = report.extractReport(IMAReport.class); - - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - final FilteredRecordsList imaRecords = - new FilteredRecordsList(); - - Long filteredResultCount = Long.valueOf(0); - - try { - tx = session.beginTransaction(); - LOGGER.debug("retrieving ima record list without records for " - + "report with id {}", id); - // The first query gets the total number of IMA - // measurement records associated with report id. - Criteria cr = session.createCriteria( - IMAMeasurementRecord.class) - .add(Restrictions.eq("report.id", imaReport.getId())) - .setProjection(Projections.countDistinct("id")); - Long totalResultCount = (Long) cr.uniqueResult(); - - // This second query finds the number of IMA - // measurement records matching the filter - cr = session.createCriteria(IMAMeasurementRecord.class) - .add(Restrictions.eq("report.id", imaReport.getId())) - .setProjection(Projections.countDistinct("id")); - - // Filter using the search terms provided by the user - Conjunction and = Restrictions.conjunction(); - if (totalResultCount != 0) { - and = buildImaRecordSearchFilter(search, searchableColumns); - cr.add(and); - filteredResultCount = (Long) cr.uniqueResult(); - } - - if (filteredResultCount != 0) { - // The third query builds a list from the filters, - // limits, and sorting options and retrieves all ima measurement - // records associated with a particular report id. - cr = session.createCriteria(IMAMeasurementRecord.class) - .add(and) - .add(Restrictions.eq("report.id", imaReport.getId())) - .setProjection(Projections.projectionList() - .add(Projections.property("hash"), "hash") - .add(Projections.property("path"), "path") - ) - .setResultTransformer(Transformers.aliasToBean( - SimpleImaRecordBean.class)) - .setFirstResult(firstResult) - .setMaxResults(maxResults); - - if (ascending) { - cr.addOrder(Order.asc(columnToOrder.getHQL())); - } else { - cr.addOrder(Order.desc(columnToOrder.getHQL())); - } - - // Perform the query and add all baselines to the list - List list = cr.list(); - for (Object o : list) { - if (o instanceof SimpleImaRecordBean) { - imaRecords.add((SimpleImaRecordBean) o); - } - } - } - - // Update meta data for the Data Table. - imaRecords.setRecordsTotal(totalResultCount); - imaRecords.setRecordsFiltered(filteredResultCount); - tx.commit(); - } catch (HibernateException e) { - final String msg = "Error getting the SimpleBaselineBean list"; - LOGGER.error(msg, e); - if (tx != null) { - LOGGER.debug("rolling back transaction"); - tx.rollback(); - } - throw e; - } finally { - if (session != null && session.isConnected()) { - session.close(); - } - } - return imaRecords; - } - - @SuppressWarnings("checkstyle:parameternumber") - private FilteredRecordsList - getImaRecordsForDevice(final String id, - final boolean sinceLastFullReport, - final IMARecordField columnToOrder, - final boolean ascending, - final int firstResult, - final int maxResults, - final String search, - final Map searchableColumns) { - List imaReportIds; - - if (sinceLastFullReport) { - imaReportIds = getImaIdsOfRecentBootCycle(id); - } else { - imaReportIds = getImaIdsOfDevice(id); - } - - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - final FilteredRecordsList imaRecords = - new FilteredRecordsList(); - - Long totalResultCount = Long.valueOf(0); - Long filteredResultCount = Long.valueOf(0); - - try { - tx = session.beginTransaction(); - LOGGER.debug("retrieving ima record list without records for " - + "device with id {}", id); - // The first query gets the total number of IMA - // measurement records associated with ima report ids. - Criteria cr = session.createCriteria( - IMAMeasurementRecord.class) - .add(Restrictions.in("report.id", imaReportIds)) - .setProjection(Projections.countDistinct("id")); - totalResultCount = (Long) cr.uniqueResult(); - - // This second query finds the number of IMA - // measurement records matching the filter - cr = session.createCriteria(IMAMeasurementRecord.class) - .add(Restrictions.in("report.id", imaReportIds)) - .setProjection(Projections.countDistinct("id")); - - // Filter using the search terms provided by the user - Conjunction and = Restrictions.conjunction(); - if (totalResultCount != 0) { - and = buildImaRecordSearchFilter(search, searchableColumns); - cr.add(and); - filteredResultCount = (Long) cr.uniqueResult(); - } - - if (filteredResultCount != 0) { - // The third query builds a list from the filters, - // limits, and sorting options - - - cr = session.createCriteria(IMAMeasurementRecord.class) - .add(and) - .add(Restrictions.in("report.id", imaReportIds)) - .setProjection(Projections.projectionList() - .add(Projections.property("hash"), "hash") - .add(Projections.property("path"), "path") - ) - .setResultTransformer(Transformers.aliasToBean( - SimpleImaRecordBean.class)) - .setFirstResult(firstResult) - .setMaxResults(maxResults); - - if (ascending) { - cr.addOrder(Order.asc(columnToOrder.getHQL())); - } else { - cr.addOrder(Order.desc(columnToOrder.getHQL())); - } - - // Perform the query and add all baselines to the list - List list = cr.list(); - for (Object o : list) { - if (o instanceof SimpleImaRecordBean) { - imaRecords.add((SimpleImaRecordBean) o); - } - } - } - - // Update meta data for the Data Table. - imaRecords.setRecordsTotal(totalResultCount); - imaRecords.setRecordsFiltered(filteredResultCount); - tx.commit(); - } catch (HibernateException e) { - final String msg = "Error getting the " + SimpleImaRecordBean.class.getSimpleName() - + " list"; - LOGGER.error(msg, e); - if (tx != null) { - LOGGER.debug("rolling back transaction"); - tx.rollback(); - } - throw e; - } finally { - if (session != null && session.isConnected()) { - session.close(); - } - } - return imaRecords; - } - - /** - * Method retrieves all ima report ids associated with the latest full ima - * report (as determined by a starting index of 0 and the most recent - * report create time) of provided device id. - * @param id of device - * @return list of IMA report ids - */ - private List getImaIdsOfRecentBootCycle(final String id) { - - ReportSummaryManager reportSummaryManager = - new DBReportSummaryManager(getFactory()); - List reportSummary = reportSummaryManager - .getReportSummaryListByHostname(id); - - List imaReports = new ArrayList<>(); - for (ReportSummary summary : reportSummary) { - IntegrityReport integrityReport = (IntegrityReport) summary - .getReport(); - imaReports.add(integrityReport.extractReport(IMAReport.class)); - } - - String bootCycleId = ""; - Date createTime = null; - List imaReportIds = new ArrayList<>(); - - // Retrieve most recent IMAReport where index is 0. - for (IMAReport report : imaReports) { - if (createTime == null) { - createTime = report.getCreateTime(); - bootCycleId = report.getBootcycleId(); - } else if (createTime.before(report.getCreateTime()) - && report.getIndex() == 0) { - createTime = report.getCreateTime(); - bootCycleId = report.getBootcycleId(); - } - } - - // Retrieve all IMAReports corresponding to bootCycleID. - for (IMAReport report : imaReports) { - if (report.getBootcycleId().equals(bootCycleId)) { - imaReportIds.add(report.getId()); - } - } - return imaReportIds; - } - - /** - * Method retrieves all ima report ids corresponding to provided - * device id. - * device. - * @param id of device - * @return list of IMA report ids - */ - private List getImaIdsOfDevice(final String id) { - - ReportSummaryManager reportSummaryManager = - new DBReportSummaryManager(getFactory()); - List reportSummary = reportSummaryManager - .getReportSummaryListByHostname(id); - - List imaReportIds = new ArrayList<>(); - for (ReportSummary summary : reportSummary) { - IntegrityReport integrityReport = (IntegrityReport) summary - .getReport(); - imaReportIds.add(integrityReport.extractReport(IMAReport.class) - .getId()); - } - return imaReportIds; - } - - private Conjunction buildImaRecordSearchFilter(final String search, final - Map searchableColumns) { - // Search for all words in all searchable columns - Conjunction and = Restrictions.conjunction(); - String[] searchWords = StringUtils.split(search); - for (String word : searchWords) { - // Every word must be in at least one column - Disjunction or = Restrictions.disjunction(); - for (Map.Entry entry - : searchableColumns.entrySet()) { - if (entry.getValue()) { - if (entry.getKey().equals("digest")) { - or.add(ilikeHex("digest", word)); - } else { - or.add(ilike(entry.getKey(), word, - MatchMode.ANYWHERE)); - } - } else { - or.add(ilikeCast(entry.getKey(), word)); - } - } - and.add(or); - } - return and; - } -} +package hirs.persist; + +import hirs.FilteredRecordsList; +import hirs.data.bean.SimpleImaRecordBean; +import hirs.data.persist.IMAMeasurementRecord; +import hirs.data.persist.IMAReport; +import hirs.data.persist.IntegrityReport; +import hirs.data.persist.Report; +import hirs.data.persist.ReportSummary; +import hirs.persist.imarecord.DbImaRecordQueryForDevice; +import hirs.persist.imarecord.DbImaRecordQueryForDeviceSinceLastFullReport; +import hirs.persist.imarecord.DbImaRecordQueryForNone; +import hirs.persist.imarecord.DbImaRecordQueryForReport; +import hirs.persist.imarecord.DbImaRecordQueryParameters; +import org.apache.commons.lang3.StringUtils; +import org.apache.logging.log4j.Logger; +import org.hibernate.Criteria; +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Conjunction; +import org.hibernate.criterion.Disjunction; +import org.hibernate.criterion.MatchMode; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.hibernate.transform.Transformers; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static org.apache.logging.log4j.LogManager.getLogger; +import static org.hibernate.criterion.Restrictions.ilike; + +/** + * This class defines a ReportManager that stores the reports in a + * database. + */ +public class DBReportManager extends DBManager implements ReportManager { + private static final Logger LOGGER = getLogger(DBReportManager.class); + + /** + * Creates a new DBReportManager that uses the provided sessionFactory + * to interact with a database. + * + * @param sessionFactory session factory used to access database connections + */ + public DBReportManager(final SessionFactory sessionFactory) { + super(Report.class, sessionFactory); + } + + /** + * Saves the Report in the database and returns it. + * + * @param report + * report to save + * @return Report that was saved + * @throws DBManagerException + * if Report has previously been saved or an error occurs while + * trying to save it to the database + */ + @Override + public final Report saveReport(final Report report) + throws DBManagerException { + LOGGER.debug("Saving report: {}", report); + try { + return super.save(report); + } catch (DBManagerException e) { + throw new ReportManagerException(e); + } + } + + /** + * Returns a list of all Reports of type clazz. + * This searches through the database for this information. + * + * All Reports will be returned without measurement records as they are + * lazily loaded for performance. If the records of a report are necessary, + * a method will need to be written to return the records inside of a + * transaction. + * + * @param clazz + * class type of Reports to return (may be null) + * @return list of Reports + * @throws ReportManagerException + * if unable to search the database + */ + @Override + public final List getReportList(final Class clazz) + throws ReportManagerException { + LOGGER.debug("getting report list"); + try { + return super.getList(clazz); + } catch (DBManagerException e) { + throw new ReportManagerException(e); + } + } + + /** + * Returns a list of all Report Records that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This + * method contains database interactions designed to extract specific + * fields from the database to avoid retrieving full records in order + * to improve query performance and reduce the size of teh data set + * returned to the caller. This method helps support the server-side + * processing in the JQuery DataTables. + * + * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE + * @param id the id or name of the REPORT or DEVICE to search + * @param sinceLastFullReport limits the records to those since the last full report for the + * device + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @param searchableColumns map containing columns that search string can + * be applied to + * @return FilteredRecordsList object with fields for DataTables + * @throws ReportManagerException if unable to create the list + */ + @Override + @SuppressWarnings("checkstyle:parameternumber") + public final FilteredRecordsList + getOrderedRecordListWithoutRecords( + final IMARecordScope scope, + final String id, + final boolean sinceLastFullReport, + final IMARecordField columnToOrder, + final boolean ascending, + final int firstResult, + final int maxResults, + final String search, + final Map searchableColumns) + throws ReportManagerException { + + // check columnToOrder + if (columnToOrder == null) { + final String msg = "columnToOrder cannot be null"; + LOGGER.error(msg); + throw new IllegalArgumentException(msg); + } + + // check scope + if (scope == null) { + throw new IllegalArgumentException("IMARecordScope cannot be null"); + } + + switch (scope) { + case NONE: + // Returns an empty FilteredRecordsList to make DataTables + // display "No Data". + return new FilteredRecordsList<>(); + case REPORT: + return getImaRecordsForReport(id, columnToOrder, ascending, + firstResult, + maxResults, search, searchableColumns); + case DEVICE: + return getImaRecordsForDevice(id, sinceLastFullReport, + columnToOrder, ascending, firstResult, + maxResults, search, searchableColumns); + default: + throw new UnsupportedOperationException( + "IMARecordScope " + scope + " is not supported"); + } + } + + /** + * Returns a list of all Report Records that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. + * + * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE + * @param id the id or name of the REPORT or DEVICE to search + * @param sinceLastFullReport limits the records to those since the last full report for the + * device + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @return FilteredRecordsList object with fields for DataTables + * @throws ReportManagerException if unable to create the list + */ + @Override + @SuppressWarnings("checkstyle:parameternumber") + public final FilteredRecordsList getOrderedRecordList( + final IMARecordScope scope, + final String id, + final boolean sinceLastFullReport, + final IMARecordField columnToOrder, + final boolean ascending, + final int firstResult, + final int maxResults, + final String search) + throws ReportManagerException { + + // check columnToOrder + if (columnToOrder == null) { + final String msg = "columnToOrder cannot be null"; + LOGGER.error(msg); + throw new IllegalArgumentException(msg); + } + + // check scope + if (scope == null) { + throw new IllegalArgumentException("IMARecordScope cannot be null"); + } + + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + try { + tx = session.beginTransaction(); + + final DbImaRecordQueryParameters params + = new DbImaRecordQueryParameters(id, columnToOrder, ascending, + firstResult, maxResults, search); + + switch (scope) { + case NONE: + return new DbImaRecordQueryForNone().query(); + case REPORT: + return new DbImaRecordQueryForReport(session, params).query(); + case DEVICE: + if (sinceLastFullReport) { + DbImaRecordQueryForDeviceSinceLastFullReport q + = new DbImaRecordQueryForDeviceSinceLastFullReport(session, params); + return q.query(); + } else { + return new DbImaRecordQueryForDevice(session, params).query(); + } + default: + throw new UnsupportedOperationException( + "IMARecordScope " + scope + " is not supported"); + } + + } catch (Exception ex) { + String msg = "Error executing IMA Record query for " + scope + " scope."; + if (scope == IMARecordScope.DEVICE) { + msg += "Since last full report = " + sinceLastFullReport; + } + LOGGER.error(msg, ex); + throw ex; + } finally { + if (tx != null) { + tx.rollback(); + } + } + + } + + /** + * Retrieves the Report from the database. This searches the + * database for an entry whose id matches id. It then + * reconstructs a Report object from the database entry. + * + * Note: IMAMeasurementRecords are lazily loaded so the object + * returned will not contain them for performance purposes. If the whole + * report needs to be retrieved a method will need to be written to return + * the records inside of a transaction. + * + * @param id id of the report + * @return report + * @throws ReportManagerException + * if unable to search the database or recreate the Report + */ + @Override + public final Report getReport(final UUID id) throws ReportManagerException { + LOGGER.debug("getting report: {}", id); + try { + return super.get(id); + } catch (DBManagerException e) { + throw new ReportManagerException(e); + } + } + + @Override + public final Report getCompleteReport(final UUID id) throws ReportManagerException { + LOGGER.debug("getting full report: {}", id); + try { + return super.getAndLoadLazyFields(id, true); + } catch (DBManagerException e) { + throw new ReportManagerException(e); + } + } + + /** + * Updates a Report. This updates the database entries + * to reflect the new values that should be set. + * + * @param report + * report to be updated + * @throws ReportManagerException + * if Report an error occurs while updating the report or + * while trying to save it to the database + */ + @Override + public void updateReport(final Report report) throws ReportManagerException { + LOGGER.debug("updating report: {}", report); + try { + super.update(report); + } catch (DBManagerException e) { + throw new ReportManagerException(e); + } + } + + /** + * Deletes the Report from the database. This removes all of + * the database entries that stored information with regards to the this + * Report. + *

+ * If the Report is referenced by any other tables then this + * will throw a ReportManagerException. + * + * @param id + * id of the Report to delete + * @return true if successfully found and deleted the Report + * @throws ReportManagerException + * if unable to find the baseline or delete it from the + * database + */ + @Override + public final boolean deleteReport(final UUID id) + throws ReportManagerException { + LOGGER.debug("deleting baseline: {}", id); + try { + return super.delete(id); + } catch (DBManagerException e) { + throw new ReportManagerException(e); + } + } + + private FilteredRecordsList + getImaRecordsForReport( + final String id, + final IMARecordField columnToOrder, + final boolean ascending, + final int firstResult, + final int maxResults, + final String search, + final Map searchableColumns) { + IntegrityReport report = (IntegrityReport) + getReport(UUID.fromString(id)); + IMAReport imaReport = report.extractReport(IMAReport.class); + + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + final FilteredRecordsList imaRecords = + new FilteredRecordsList(); + + Long filteredResultCount = Long.valueOf(0); + + try { + tx = session.beginTransaction(); + LOGGER.debug("retrieving ima record list without records for " + + "report with id {}", id); + // The first query gets the total number of IMA + // measurement records associated with report id. + Criteria cr = session.createCriteria( + IMAMeasurementRecord.class) + .add(Restrictions.eq("report.id", imaReport.getId())) + .setProjection(Projections.countDistinct("id")); + Long totalResultCount = (Long) cr.uniqueResult(); + + // This second query finds the number of IMA + // measurement records matching the filter + cr = session.createCriteria(IMAMeasurementRecord.class) + .add(Restrictions.eq("report.id", imaReport.getId())) + .setProjection(Projections.countDistinct("id")); + + // Filter using the search terms provided by the user + Conjunction and = Restrictions.conjunction(); + if (totalResultCount != 0) { + and = buildImaRecordSearchFilter(search, searchableColumns); + cr.add(and); + filteredResultCount = (Long) cr.uniqueResult(); + } + + if (filteredResultCount != 0) { + // The third query builds a list from the filters, + // limits, and sorting options and retrieves all ima measurement + // records associated with a particular report id. + cr = session.createCriteria(IMAMeasurementRecord.class) + .add(and) + .add(Restrictions.eq("report.id", imaReport.getId())) + .setProjection(Projections.projectionList() + .add(Projections.property("hash"), "hash") + .add(Projections.property("path"), "path") + ) + .setResultTransformer(Transformers.aliasToBean( + SimpleImaRecordBean.class)) + .setFirstResult(firstResult) + .setMaxResults(maxResults); + + if (ascending) { + cr.addOrder(Order.asc(columnToOrder.getHQL())); + } else { + cr.addOrder(Order.desc(columnToOrder.getHQL())); + } + + // Perform the query and add all baselines to the list + List list = cr.list(); + for (Object o : list) { + if (o instanceof SimpleImaRecordBean) { + imaRecords.add((SimpleImaRecordBean) o); + } + } + } + + // Update meta data for the Data Table. + imaRecords.setRecordsTotal(totalResultCount); + imaRecords.setRecordsFiltered(filteredResultCount); + tx.commit(); + } catch (HibernateException e) { + final String msg = "Error getting the SimpleBaselineBean list"; + LOGGER.error(msg, e); + if (tx != null) { + LOGGER.debug("rolling back transaction"); + tx.rollback(); + } + throw e; + } finally { + if (session != null && session.isConnected()) { + session.close(); + } + } + return imaRecords; + } + + @SuppressWarnings("checkstyle:parameternumber") + private FilteredRecordsList + getImaRecordsForDevice(final String id, + final boolean sinceLastFullReport, + final IMARecordField columnToOrder, + final boolean ascending, + final int firstResult, + final int maxResults, + final String search, + final Map searchableColumns) { + List imaReportIds; + + if (sinceLastFullReport) { + imaReportIds = getImaIdsOfRecentBootCycle(id); + } else { + imaReportIds = getImaIdsOfDevice(id); + } + + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + final FilteredRecordsList imaRecords = + new FilteredRecordsList(); + + Long totalResultCount = Long.valueOf(0); + Long filteredResultCount = Long.valueOf(0); + + try { + tx = session.beginTransaction(); + LOGGER.debug("retrieving ima record list without records for " + + "device with id {}", id); + // The first query gets the total number of IMA + // measurement records associated with ima report ids. + Criteria cr = session.createCriteria( + IMAMeasurementRecord.class) + .add(Restrictions.in("report.id", imaReportIds)) + .setProjection(Projections.countDistinct("id")); + totalResultCount = (Long) cr.uniqueResult(); + + // This second query finds the number of IMA + // measurement records matching the filter + cr = session.createCriteria(IMAMeasurementRecord.class) + .add(Restrictions.in("report.id", imaReportIds)) + .setProjection(Projections.countDistinct("id")); + + // Filter using the search terms provided by the user + Conjunction and = Restrictions.conjunction(); + if (totalResultCount != 0) { + and = buildImaRecordSearchFilter(search, searchableColumns); + cr.add(and); + filteredResultCount = (Long) cr.uniqueResult(); + } + + if (filteredResultCount != 0) { + // The third query builds a list from the filters, + // limits, and sorting options + + + cr = session.createCriteria(IMAMeasurementRecord.class) + .add(and) + .add(Restrictions.in("report.id", imaReportIds)) + .setProjection(Projections.projectionList() + .add(Projections.property("hash"), "hash") + .add(Projections.property("path"), "path") + ) + .setResultTransformer(Transformers.aliasToBean( + SimpleImaRecordBean.class)) + .setFirstResult(firstResult) + .setMaxResults(maxResults); + + if (ascending) { + cr.addOrder(Order.asc(columnToOrder.getHQL())); + } else { + cr.addOrder(Order.desc(columnToOrder.getHQL())); + } + + // Perform the query and add all baselines to the list + List list = cr.list(); + for (Object o : list) { + if (o instanceof SimpleImaRecordBean) { + imaRecords.add((SimpleImaRecordBean) o); + } + } + } + + // Update meta data for the Data Table. + imaRecords.setRecordsTotal(totalResultCount); + imaRecords.setRecordsFiltered(filteredResultCount); + tx.commit(); + } catch (HibernateException e) { + final String msg = "Error getting the " + SimpleImaRecordBean.class.getSimpleName() + + " list"; + LOGGER.error(msg, e); + if (tx != null) { + LOGGER.debug("rolling back transaction"); + tx.rollback(); + } + throw e; + } finally { + if (session != null && session.isConnected()) { + session.close(); + } + } + return imaRecords; + } + + /** + * Method retrieves all ima report ids associated with the latest full ima + * report (as determined by a starting index of 0 and the most recent + * report create time) of provided device id. + * @param id of device + * @return list of IMA report ids + */ + private List getImaIdsOfRecentBootCycle(final String id) { + + ReportSummaryManager reportSummaryManager = + new DBReportSummaryManager(getFactory()); + List reportSummary = reportSummaryManager + .getReportSummaryListByHostname(id); + + List imaReports = new ArrayList<>(); + for (ReportSummary summary : reportSummary) { + IntegrityReport integrityReport = (IntegrityReport) summary + .getReport(); + imaReports.add(integrityReport.extractReport(IMAReport.class)); + } + + String bootCycleId = ""; + Date createTime = null; + List imaReportIds = new ArrayList<>(); + + // Retrieve most recent IMAReport where index is 0. + for (IMAReport report : imaReports) { + if (createTime == null) { + createTime = report.getCreateTime(); + bootCycleId = report.getBootcycleId(); + } else if (createTime.before(report.getCreateTime()) + && report.getIndex() == 0) { + createTime = report.getCreateTime(); + bootCycleId = report.getBootcycleId(); + } + } + + // Retrieve all IMAReports corresponding to bootCycleID. + for (IMAReport report : imaReports) { + if (report.getBootcycleId().equals(bootCycleId)) { + imaReportIds.add(report.getId()); + } + } + return imaReportIds; + } + + /** + * Method retrieves all ima report ids corresponding to provided + * device id. + * device. + * @param id of device + * @return list of IMA report ids + */ + private List getImaIdsOfDevice(final String id) { + + ReportSummaryManager reportSummaryManager = + new DBReportSummaryManager(getFactory()); + List reportSummary = reportSummaryManager + .getReportSummaryListByHostname(id); + + List imaReportIds = new ArrayList<>(); + for (ReportSummary summary : reportSummary) { + IntegrityReport integrityReport = (IntegrityReport) summary + .getReport(); + imaReportIds.add(integrityReport.extractReport(IMAReport.class) + .getId()); + } + return imaReportIds; + } + + private Conjunction buildImaRecordSearchFilter(final String search, final + Map searchableColumns) { + // Search for all words in all searchable columns + Conjunction and = Restrictions.conjunction(); + String[] searchWords = StringUtils.split(search); + for (String word : searchWords) { + // Every word must be in at least one column + Disjunction or = Restrictions.disjunction(); + for (Map.Entry entry + : searchableColumns.entrySet()) { + if (entry.getValue()) { + if (entry.getKey().equals("digest")) { + or.add(ilikeHex("digest", word)); + } else { + or.add(ilike(entry.getKey(), word, + MatchMode.ANYWHERE)); + } + } else { + or.add(ilikeCast(entry.getKey(), word)); + } + } + and.add(or); + } + return and; + } +} diff --git a/HIRS_Utils/src/main/java/hirs/persist/DBReportSummaryManager.java b/HIRS_Utils/src/main/java/hirs/persist/DBReportSummaryManager.java index 1a03b9198..9392b59a2 100755 --- a/HIRS_Utils/src/main/java/hirs/persist/DBReportSummaryManager.java +++ b/HIRS_Utils/src/main/java/hirs/persist/DBReportSummaryManager.java @@ -1,443 +1,443 @@ -package hirs.persist; - -import hirs.FilteredRecordsList; -import static org.apache.logging.log4j.LogManager.getLogger; -import hirs.data.persist.ReportSummary; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import org.apache.commons.lang3.StringUtils; - -import org.apache.logging.log4j.Logger; -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.criterion.DetachedCriteria; -import org.hibernate.criterion.Order; -import org.hibernate.criterion.ProjectionList; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.hibernate.criterion.Subqueries; - -/** - * This class defines a DBReportSummaryManager that stores the - * report - * summary in a database. - */ -public class DBReportSummaryManager extends DBManager - implements ReportSummaryManager { - - private static final Logger LOGGER = getLogger(DBReportSummaryManager.class); - - /** - * Creates a new DBReportSummaryManager that uses the default - * database. - * The default database is used to store all of the - * ReportSummary objects. - * - * @param sessionFactory session factory used to access database connections - */ - public DBReportSummaryManager(final SessionFactory sessionFactory) { - super(ReportSummary.class, sessionFactory); - } - - /** - * Saves the ReportSummary in the database and returns it. - * - * @param report - * report summary to save - * @return ReportSummary that was saved - * @throws ReportSummaryManagerException - * if ReportSummary has previously been saved or an error - * occurs while trying to save it to the database - */ - @Override - public final ReportSummary saveReportSummary(final ReportSummary report) - throws ReportSummaryManagerException { - LOGGER.debug("Saving ReportSummary: {}", report); - try { - return super.save(report); - } catch (DBManagerException e) { - throw new ReportSummaryManagerException(e); - } - } - - /** - * Updates a ReportSummary. This updates the database entries - * to reflect the new values that should be set. - * - * @param report - * report - * @throws ReportSummaryManagerException - * if Report has not previously been saved or an error occurs - * while trying to save it to the database - */ - @Override - public final void updateReportSummary(final ReportSummary report) - throws ReportSummaryManagerException { - LOGGER.debug("updating ReportSummary: {}", report); - try { - super.update(report); - } catch (DBManagerException e) { - throw new ReportSummaryManagerException(e); - } - } - - /** - * Returns a list of all ReportSummarys of type - * clazz. This searches through the database for this - * information. - * - * @param clazz - * class type of ReportSummarys to return (may be - * null) - * @return list of ReportSummarys - * @throws ReportSummaryManagerException - * if unable to search the database - */ - @Override - public final List getReportSummaryList( - final Class clazz) - throws ReportSummaryManagerException { - LOGGER.debug("getting ReportSummary list"); - try { - return super.getList(clazz); - } catch (DBManagerException e) { - throw new ReportSummaryManagerException(e); - } - } - - /** - * Returns a list of ReportSummarys of type - * clazz that share the provided hostname. This - * searches through the database for this information. - * - * @param hostname - * hostname for the machine in which the - * ReportSummary was generated for. - * @return list of ReportSummarys - * @throws ReportSummaryManagerException - * if unable to search the database - */ - @Override - public final List getReportSummaryListByHostname( - final String hostname) throws ReportSummaryManagerException { - LOGGER.debug("getting ReportSummary hostname list"); - - if (hostname == null) { - LOGGER.debug("hostname was null"); - throw new ReportSummaryManagerException( - "Hostname provided was null"); - } - - List reportSummaryList = new ArrayList<>(); - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - try { - LOGGER.debug("retrieving objects from db"); - tx = session.beginTransaction(); - List list = session.createCriteria(ReportSummary.class) - .add(Restrictions.eq("clientHostname", hostname)) - .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) - .list(); - - for (Object o : list) { - if (o instanceof ReportSummary) { - reportSummaryList.add((ReportSummary) o); - } - } - - tx.commit(); - } catch (Exception e) { - final String msg = "unable to retrieve query list"; - LOGGER.error(msg, e); - if (tx != null) { - LOGGER.debug("rolling back transaction"); - tx.rollback(); - } - throw new ReportSummaryManagerException(e); - } - return reportSummaryList; - } - - /** - * Returns a list of all ReportSummary objects that are ordered - * by a column and direction (ASC, DESC) that is provided by the user. This - * method helps support the server-side processing in the JQuery DataTables. - * - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @param searchableColumns Map of String and boolean values with column - * headers and whether they are to. Boolean is true if field provides - * a typical String that can be searched by Hibernate without - * transformation. - * @param hostname name of the device to filter on - * @return FilteredRecordsList object with fields for DataTables - * @throws ReportSummaryManagerException - * if unable to create the list - */ - @Override - public final FilteredRecordsList getOrderedReportSummaryList( - final String columnToOrder, final boolean ascending, final int firstResult, - final int maxResults, final String search, - final Map searchableColumns, - final String hostname) throws ReportSummaryManagerException { - if (columnToOrder == null) { - LOGGER.debug("null object argument"); - throw new NullPointerException("object"); - } - - // allows filtering by specific hostname. If no hostname specified, always match. - CriteriaModifier modifier = new CriteriaModifier() { - @Override - public void modify(final Criteria criteria) { - criteria.add(Restrictions.ilike("clientHostname", - StringUtils.defaultIfBlank(hostname, "%"))); - } - }; - - LOGGER.debug("Getting report summary list"); - final FilteredRecordsList summaries; - try { - summaries = super.getOrderedList(ReportSummary.class, columnToOrder, - ascending, firstResult, maxResults, search, - searchableColumns, modifier); - } catch (DBManagerException e) { - throw new BaselineManagerException(e); - } - LOGGER.debug("Got {} report summaries", summaries.size()); - return summaries; - } - /** - * Retrieves the ReportSummary from the database. This - * searches the database for an entry whose id matches id. - * It then reconstructs a ReportSummary object from the - * database entry - * - * @param id - * id of the ReportSummary - * @return ReportSummary if found, otherwise null. - * @throws ReportSummaryManagerException - * if unable to search the database or recreate the - * ReportSummary - */ - @Override - public final ReportSummary getReportSummary(final long id) - throws ReportSummaryManagerException { - LOGGER.debug("getting ReportSummary: {}", id); - try { - return super.get(id); - } catch (DBManagerException e) { - throw new ReportSummaryManagerException(e); - } - } - - /** - * Retrieves the ReportSummary identified by the - * Report's id. If the ReportSummary - * cannot be found then null is returned. - * - * @param id - * UUID of the Report - * @return ReportSummary whose Report's - * UUID is id or null if not found - */ - @Override - public final ReportSummary getReportSummaryByReportID(final UUID id) { - LOGGER.debug("getting ReportSummary that matches uuid"); - - if (id == null) { - LOGGER.debug("id provided was null"); - throw new ReportSummaryManagerException( - "id provided was null"); - } - - ReportSummary object; - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - try { - LOGGER.debug("retrieving objects from db"); - tx = session.beginTransaction(); - object = (ReportSummary) session - .createCriteria(ReportSummary.class) - .add(Restrictions.eq("report.id", id)) - .uniqueResult(); - tx.commit(); - } catch (Exception e) { - final String msg = "unable to retrieve query list"; - LOGGER.error(msg, e); - if (tx != null) { - LOGGER.debug("rolling back transaction"); - tx.rollback(); - } - throw new ReportSummaryManagerException(e); - } - return object; - } - - /** - * Deletes the ReportSummary from the database. This removes - * all of the database entries that stored information with regards to the - * this ReportSummary. - *

- * If the ReportSummary is referenced by any other tables then - * this will throw a ReportSummaryManagerException. - * - * @param id - * id of the ReportSummary to delete - * @return true if successfully found and deleted the - * ReportSummary - * @throws ReportSummaryManagerException - * if unable to find the baseline or delete it from the - * database - */ - @Override - public final boolean deleteReportSummary(final Long id) - throws ReportSummaryManagerException { - LOGGER.debug("deleting report summary: {}", id); - try { - return super.delete(id); - } catch (DBManagerException e) { - throw new ReportSummaryManagerException(e); - } - } - - /** - * Returns a list of ReportSummarys that contains the latest - * report from each client. This searches through the database for this - * information. - * - * @return list of ReportSummarys - * @throws ReportSummaryManagerException - * if unable to search the database - */ - @Override - public final List getUniqueClientLatestReportList() - throws ReportSummaryManagerException { - LOGGER.debug("getting latest reports for all clients"); - - List reportSummaryList = new ArrayList<>(); - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - try { - LOGGER.debug("retrieving objects from db"); - tx = session.beginTransaction(); - DetachedCriteria uniqueHosts = DetachedCriteria.forClass( - ReportSummary.class); - - ProjectionList properties = Projections.projectionList(); - properties.add(Projections.groupProperty("clientHostname")); - properties.add(Projections.max("timestamp"), "timestamp"); - - uniqueHosts.setProjection(properties); - - List list = session.createCriteria(ReportSummary.class) - .add(Subqueries.propertiesIn( - new String[]{"clientHostname", "timestamp"}, - uniqueHosts)) - .list(); - for (Object o : list) { - if (o instanceof ReportSummary) { - reportSummaryList.add((ReportSummary) o); - } - } - tx.commit(); - } catch (Exception e) { - final String msg = "unable to retrieve query list"; - LOGGER.error(msg, e); - if (tx != null) { - LOGGER.debug("rolling back transaction"); - tx.rollback(); - } - throw new ReportSummaryManagerException(e); - } - return reportSummaryList; - } - - /** - * Retrieves the newest report timestamp for a given hostname. - * @param hostname - * hostname of client to be checked for - * @return newest timestamp from matching ReportSummaries - * @throws ReportSummaryManagerException - * if unable to return a timestamp - */ - @Override - public final ReportSummary getNewestReport(final String hostname) - throws ReportSummaryManagerException { - LOGGER.debug("getting newest report timestamp for: " + hostname); - - if (hostname == null) { - LOGGER.debug("hostname was null, trying to return generic list"); - throw new ReportSummaryManagerException( - "Hostname provided was null"); - } - - //Sets the order so the first result is the most recent Timestamp - Order order = Order.desc("timestamp"); - - return getReportTimestamp(hostname, order); - } - - /** - * Retrieves the newest report timestamp for a given hostname. - * @param hostname - * hostname of client to be checked for - * @return newest timestamp from matching ReportSummaries - * @throws ReportSummaryManagerException - * if unable to return a timestamp - */ - @Override - public final ReportSummary getFirstReport(final String hostname) - throws ReportSummaryManagerException { - LOGGER.debug("getting newest report timestamp for: " + hostname); - - if (hostname == null) { - LOGGER.debug("hostname was null, trying to return generic list"); - throw new ReportSummaryManagerException( - "Hostname provided was null"); - } - - //Sets the order so the first result is oldest timestamp - Order order = Order.asc("timestamp"); - - return getReportTimestamp(hostname, order); - } - - private ReportSummary getReportTimestamp(final String hostname, - final Order order) throws ReportSummaryManagerException { - final int firstResult = 0; - final int uniqueResult = 1; - - ReportSummary object; - Transaction tx = null; - Session session = getFactory().getCurrentSession(); - try { - LOGGER.debug("retrieving objects from db"); - tx = session.beginTransaction(); - //Returns a ReportSummary based on the timestamp and hostname - object = (ReportSummary) session.createCriteria(ReportSummary.class) - .addOrder(order) - .add(Restrictions.eq("clientHostname", hostname)) - .setFirstResult(firstResult) - .setMaxResults(uniqueResult) - .uniqueResult(); - tx.commit(); - } catch (Exception e) { - final String msg = "unable to retrieve query list"; - LOGGER.error(msg, e); - if (tx != null) { - LOGGER.debug("rolling back transaction"); - tx.rollback(); - } - throw new ReportSummaryManagerException(e); - } - return object; - } -} +package hirs.persist; + +import hirs.FilteredRecordsList; +import static org.apache.logging.log4j.LogManager.getLogger; +import hirs.data.persist.ReportSummary; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.lang3.StringUtils; + +import org.apache.logging.log4j.Logger; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.DetachedCriteria; +import org.hibernate.criterion.Order; +import org.hibernate.criterion.ProjectionList; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.hibernate.criterion.Subqueries; + +/** + * This class defines a DBReportSummaryManager that stores the + * report + * summary in a database. + */ +public class DBReportSummaryManager extends DBManager + implements ReportSummaryManager { + + private static final Logger LOGGER = getLogger(DBReportSummaryManager.class); + + /** + * Creates a new DBReportSummaryManager that uses the default + * database. + * The default database is used to store all of the + * ReportSummary objects. + * + * @param sessionFactory session factory used to access database connections + */ + public DBReportSummaryManager(final SessionFactory sessionFactory) { + super(ReportSummary.class, sessionFactory); + } + + /** + * Saves the ReportSummary in the database and returns it. + * + * @param report + * report summary to save + * @return ReportSummary that was saved + * @throws ReportSummaryManagerException + * if ReportSummary has previously been saved or an error + * occurs while trying to save it to the database + */ + @Override + public final ReportSummary saveReportSummary(final ReportSummary report) + throws ReportSummaryManagerException { + LOGGER.debug("Saving ReportSummary: {}", report); + try { + return super.save(report); + } catch (DBManagerException e) { + throw new ReportSummaryManagerException(e); + } + } + + /** + * Updates a ReportSummary. This updates the database entries + * to reflect the new values that should be set. + * + * @param report + * report + * @throws ReportSummaryManagerException + * if Report has not previously been saved or an error occurs + * while trying to save it to the database + */ + @Override + public final void updateReportSummary(final ReportSummary report) + throws ReportSummaryManagerException { + LOGGER.debug("updating ReportSummary: {}", report); + try { + super.update(report); + } catch (DBManagerException e) { + throw new ReportSummaryManagerException(e); + } + } + + /** + * Returns a list of all ReportSummarys of type + * clazz. This searches through the database for this + * information. + * + * @param clazz + * class type of ReportSummarys to return (may be + * null) + * @return list of ReportSummarys + * @throws ReportSummaryManagerException + * if unable to search the database + */ + @Override + public final List getReportSummaryList( + final Class clazz) + throws ReportSummaryManagerException { + LOGGER.debug("getting ReportSummary list"); + try { + return super.getList(clazz); + } catch (DBManagerException e) { + throw new ReportSummaryManagerException(e); + } + } + + /** + * Returns a list of ReportSummarys of type + * clazz that share the provided hostname. This + * searches through the database for this information. + * + * @param hostname + * hostname for the machine in which the + * ReportSummary was generated for. + * @return list of ReportSummarys + * @throws ReportSummaryManagerException + * if unable to search the database + */ + @Override + public final List getReportSummaryListByHostname( + final String hostname) throws ReportSummaryManagerException { + LOGGER.debug("getting ReportSummary hostname list"); + + if (hostname == null) { + LOGGER.debug("hostname was null"); + throw new ReportSummaryManagerException( + "Hostname provided was null"); + } + + List reportSummaryList = new ArrayList<>(); + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + try { + LOGGER.debug("retrieving objects from db"); + tx = session.beginTransaction(); + List list = session.createCriteria(ReportSummary.class) + .add(Restrictions.eq("clientHostname", hostname)) + .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY) + .list(); + + for (Object o : list) { + if (o instanceof ReportSummary) { + reportSummaryList.add((ReportSummary) o); + } + } + + tx.commit(); + } catch (Exception e) { + final String msg = "unable to retrieve query list"; + LOGGER.error(msg, e); + if (tx != null) { + LOGGER.debug("rolling back transaction"); + tx.rollback(); + } + throw new ReportSummaryManagerException(e); + } + return reportSummaryList; + } + + /** + * Returns a list of all ReportSummary objects that are ordered + * by a column and direction (ASC, DESC) that is provided by the user. This + * method helps support the server-side processing in the JQuery DataTables. + * + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @param searchableColumns Map of String and boolean values with column + * headers and whether they are to. Boolean is true if field provides + * a typical String that can be searched by Hibernate without + * transformation. + * @param hostname name of the device to filter on + * @return FilteredRecordsList object with fields for DataTables + * @throws ReportSummaryManagerException + * if unable to create the list + */ + @Override + public final FilteredRecordsList getOrderedReportSummaryList( + final String columnToOrder, final boolean ascending, final int firstResult, + final int maxResults, final String search, + final Map searchableColumns, + final String hostname) throws ReportSummaryManagerException { + if (columnToOrder == null) { + LOGGER.debug("null object argument"); + throw new NullPointerException("object"); + } + + // allows filtering by specific hostname. If no hostname specified, always match. + CriteriaModifier modifier = new CriteriaModifier() { + @Override + public void modify(final Criteria criteria) { + criteria.add(Restrictions.ilike("clientHostname", + StringUtils.defaultIfBlank(hostname, "%"))); + } + }; + + LOGGER.debug("Getting report summary list"); + final FilteredRecordsList summaries; + try { + summaries = super.getOrderedList(ReportSummary.class, columnToOrder, + ascending, firstResult, maxResults, search, + searchableColumns, modifier); + } catch (DBManagerException e) { + throw new BaselineManagerException(e); + } + LOGGER.debug("Got {} report summaries", summaries.size()); + return summaries; + } + /** + * Retrieves the ReportSummary from the database. This + * searches the database for an entry whose id matches id. + * It then reconstructs a ReportSummary object from the + * database entry + * + * @param id + * id of the ReportSummary + * @return ReportSummary if found, otherwise null. + * @throws ReportSummaryManagerException + * if unable to search the database or recreate the + * ReportSummary + */ + @Override + public final ReportSummary getReportSummary(final long id) + throws ReportSummaryManagerException { + LOGGER.debug("getting ReportSummary: {}", id); + try { + return super.get(id); + } catch (DBManagerException e) { + throw new ReportSummaryManagerException(e); + } + } + + /** + * Retrieves the ReportSummary identified by the + * Report's id. If the ReportSummary + * cannot be found then null is returned. + * + * @param id + * UUID of the Report + * @return ReportSummary whose Report's + * UUID is id or null if not found + */ + @Override + public final ReportSummary getReportSummaryByReportID(final UUID id) { + LOGGER.debug("getting ReportSummary that matches uuid"); + + if (id == null) { + LOGGER.debug("id provided was null"); + throw new ReportSummaryManagerException( + "id provided was null"); + } + + ReportSummary object; + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + try { + LOGGER.debug("retrieving objects from db"); + tx = session.beginTransaction(); + object = (ReportSummary) session + .createCriteria(ReportSummary.class) + .add(Restrictions.eq("report.id", id)) + .uniqueResult(); + tx.commit(); + } catch (Exception e) { + final String msg = "unable to retrieve query list"; + LOGGER.error(msg, e); + if (tx != null) { + LOGGER.debug("rolling back transaction"); + tx.rollback(); + } + throw new ReportSummaryManagerException(e); + } + return object; + } + + /** + * Deletes the ReportSummary from the database. This removes + * all of the database entries that stored information with regards to the + * this ReportSummary. + *

+ * If the ReportSummary is referenced by any other tables then + * this will throw a ReportSummaryManagerException. + * + * @param id + * id of the ReportSummary to delete + * @return true if successfully found and deleted the + * ReportSummary + * @throws ReportSummaryManagerException + * if unable to find the baseline or delete it from the + * database + */ + @Override + public final boolean deleteReportSummary(final Long id) + throws ReportSummaryManagerException { + LOGGER.debug("deleting report summary: {}", id); + try { + return super.delete(id); + } catch (DBManagerException e) { + throw new ReportSummaryManagerException(e); + } + } + + /** + * Returns a list of ReportSummarys that contains the latest + * report from each client. This searches through the database for this + * information. + * + * @return list of ReportSummarys + * @throws ReportSummaryManagerException + * if unable to search the database + */ + @Override + public final List getUniqueClientLatestReportList() + throws ReportSummaryManagerException { + LOGGER.debug("getting latest reports for all clients"); + + List reportSummaryList = new ArrayList<>(); + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + try { + LOGGER.debug("retrieving objects from db"); + tx = session.beginTransaction(); + DetachedCriteria uniqueHosts = DetachedCriteria.forClass( + ReportSummary.class); + + ProjectionList properties = Projections.projectionList(); + properties.add(Projections.groupProperty("clientHostname")); + properties.add(Projections.max("timestamp"), "timestamp"); + + uniqueHosts.setProjection(properties); + + List list = session.createCriteria(ReportSummary.class) + .add(Subqueries.propertiesIn( + new String[]{"clientHostname", "timestamp"}, + uniqueHosts)) + .list(); + for (Object o : list) { + if (o instanceof ReportSummary) { + reportSummaryList.add((ReportSummary) o); + } + } + tx.commit(); + } catch (Exception e) { + final String msg = "unable to retrieve query list"; + LOGGER.error(msg, e); + if (tx != null) { + LOGGER.debug("rolling back transaction"); + tx.rollback(); + } + throw new ReportSummaryManagerException(e); + } + return reportSummaryList; + } + + /** + * Retrieves the newest report timestamp for a given hostname. + * @param hostname + * hostname of client to be checked for + * @return newest timestamp from matching ReportSummaries + * @throws ReportSummaryManagerException + * if unable to return a timestamp + */ + @Override + public final ReportSummary getNewestReport(final String hostname) + throws ReportSummaryManagerException { + LOGGER.debug("getting newest report timestamp for: " + hostname); + + if (hostname == null) { + LOGGER.debug("hostname was null, trying to return generic list"); + throw new ReportSummaryManagerException( + "Hostname provided was null"); + } + + //Sets the order so the first result is the most recent Timestamp + Order order = Order.desc("timestamp"); + + return getReportTimestamp(hostname, order); + } + + /** + * Retrieves the newest report timestamp for a given hostname. + * @param hostname + * hostname of client to be checked for + * @return newest timestamp from matching ReportSummaries + * @throws ReportSummaryManagerException + * if unable to return a timestamp + */ + @Override + public final ReportSummary getFirstReport(final String hostname) + throws ReportSummaryManagerException { + LOGGER.debug("getting newest report timestamp for: " + hostname); + + if (hostname == null) { + LOGGER.debug("hostname was null, trying to return generic list"); + throw new ReportSummaryManagerException( + "Hostname provided was null"); + } + + //Sets the order so the first result is oldest timestamp + Order order = Order.asc("timestamp"); + + return getReportTimestamp(hostname, order); + } + + private ReportSummary getReportTimestamp(final String hostname, + final Order order) throws ReportSummaryManagerException { + final int firstResult = 0; + final int uniqueResult = 1; + + ReportSummary object; + Transaction tx = null; + Session session = getFactory().getCurrentSession(); + try { + LOGGER.debug("retrieving objects from db"); + tx = session.beginTransaction(); + //Returns a ReportSummary based on the timestamp and hostname + object = (ReportSummary) session.createCriteria(ReportSummary.class) + .addOrder(order) + .add(Restrictions.eq("clientHostname", hostname)) + .setFirstResult(firstResult) + .setMaxResults(uniqueResult) + .uniqueResult(); + tx.commit(); + } catch (Exception e) { + final String msg = "unable to retrieve query list"; + LOGGER.error(msg, e); + if (tx != null) { + LOGGER.debug("rolling back transaction"); + tx.rollback(); + } + throw new ReportSummaryManagerException(e); + } + return object; + } +} diff --git a/HIRS_Utils/src/main/java/hirs/persist/ReportManager.java b/HIRS_Utils/src/main/java/hirs/persist/ReportManager.java index 85a14800a..6ff079232 100755 --- a/HIRS_Utils/src/main/java/hirs/persist/ReportManager.java +++ b/HIRS_Utils/src/main/java/hirs/persist/ReportManager.java @@ -1,155 +1,155 @@ -package hirs.persist; - -import hirs.FilteredRecordsList; -import hirs.data.bean.SimpleImaRecordBean; -import hirs.data.persist.IMAMeasurementRecord; -import hirs.data.persist.Report; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * A ReportManager manages Report objects. A - * ReportManager is used to store and manage reports. It has - * support for the basic create, read, update, and delete methods. - */ -public interface ReportManager { - - /** - * Stores a new Report. This stores a new Report - * to be managed by the ReportManager. If the - * Report is successfully saved then a reference to it is - * returned. - * @param report - * Report to save - * @return reference to saved Report - * @throws ReportManagerException - * if the Report has previously been saved or unexpected error - * occurs - */ - Report saveReport(Report report) throws ReportManagerException; - - /** - * Returns a list of all Reports managed by this manager. A - * Class argument may be specified to limit which types of - * Reports to return. This argument may be null to return all - * Reports. - * - * @param clazz - * class type of Reports to return (may be null) - * @return list of all managed Report objects - * @throws ReportManagerException - * if unable to create the list - */ - List getReportList(Class clazz) - throws ReportManagerException; - - /** - * Returns a list of all Report Records that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This - * method contains database interactions designed to extract specific - * fields from the database to avoid retrieving full records in order - * to improve query performance and reduce the size of teh data set - * returned to the caller. This method helps support the server-side - * processing in the JQuery DataTables. - * - * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE - * @param id the id or name of the REPORT or DEVICE to search - * @param sinceLastFullReport - * limits the records to those since the last full report for the device - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @param searchableColumns map containing columns that search string can - * be applied to - * @return FilteredRecordsList object with fields for DataTables - * @throws ReportManagerException if unable to create the list - */ - @SuppressWarnings("checkstyle:parameternumber") - FilteredRecordsList getOrderedRecordListWithoutRecords( - IMARecordScope scope, - String id, - boolean sinceLastFullReport, - IMARecordField columnToOrder, - boolean ascending, - int firstResult, - int maxResults, - String search, - Map searchableColumns) - throws ReportManagerException; - - /** - * Returns a list of all Report Records that are ordered by a column - * and direction (ASC, DESC) that is provided by the user. This method - * helps support the server-side processing in the JQuery DataTables. - * - * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE - * @param id the id or name of the REPORT or DEVICE to search - * @param sinceLastFullReport - * limits the records to those since the last full report for the device - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @return FilteredRecordsList object with fields for DataTables - * @throws ReportManagerException if unable to create the list - */ - @SuppressWarnings("checkstyle:parameternumber") - FilteredRecordsList getOrderedRecordList( - IMARecordScope scope, - String id, - boolean sinceLastFullReport, - IMARecordField columnToOrder, - boolean ascending, - int firstResult, - int maxResults, - String search) - throws ReportManagerException; - - /** - * Retrieves the Report identified by id. - * - * @param id id of the Report - * @return Report whose name is name - * @throws ReportManagerException if unable to retrieve the Report - */ - Report getReport(UUID id) throws ReportManagerException; - - /** - * Retrieves the Report identified by id. This method - * fully loads a Report object; any lazy fields will be recursively loaded. - * - * @param id id of the Report - * @return Report whose name is name - * @throws ReportManagerException if unable to retrieve the Report - */ - Report getCompleteReport(UUID id) throws ReportManagerException; - - /** - * Updates the contents of the Report. - * - * @param report - * report to be updated - * @throws ReportManagerException - * if any unexpected errors occur while trying to update the report - */ - void updateReport(Report report) throws ReportManagerException; - - /** - * Deletes the Report identified by id. If the - * Report is found and deleted then true is returned, otherwise - * false. - * - * @param id - * id of Report to be deleted - * @return true if successfully found and deleted from repo, otherwise false - * @throws ReportManagerException - * if unable to delete the Report for any reason other than not - * found - */ - boolean deleteReport(UUID id) throws ReportManagerException; -} +package hirs.persist; + +import hirs.FilteredRecordsList; +import hirs.data.bean.SimpleImaRecordBean; +import hirs.data.persist.IMAMeasurementRecord; +import hirs.data.persist.Report; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * A ReportManager manages Report objects. A + * ReportManager is used to store and manage reports. It has + * support for the basic create, read, update, and delete methods. + */ +public interface ReportManager { + + /** + * Stores a new Report. This stores a new Report + * to be managed by the ReportManager. If the + * Report is successfully saved then a reference to it is + * returned. + * @param report + * Report to save + * @return reference to saved Report + * @throws ReportManagerException + * if the Report has previously been saved or unexpected error + * occurs + */ + Report saveReport(Report report) throws ReportManagerException; + + /** + * Returns a list of all Reports managed by this manager. A + * Class argument may be specified to limit which types of + * Reports to return. This argument may be null to return all + * Reports. + * + * @param clazz + * class type of Reports to return (may be null) + * @return list of all managed Report objects + * @throws ReportManagerException + * if unable to create the list + */ + List getReportList(Class clazz) + throws ReportManagerException; + + /** + * Returns a list of all Report Records that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This + * method contains database interactions designed to extract specific + * fields from the database to avoid retrieving full records in order + * to improve query performance and reduce the size of teh data set + * returned to the caller. This method helps support the server-side + * processing in the JQuery DataTables. + * + * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE + * @param id the id or name of the REPORT or DEVICE to search + * @param sinceLastFullReport + * limits the records to those since the last full report for the device + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @param searchableColumns map containing columns that search string can + * be applied to + * @return FilteredRecordsList object with fields for DataTables + * @throws ReportManagerException if unable to create the list + */ + @SuppressWarnings("checkstyle:parameternumber") + FilteredRecordsList getOrderedRecordListWithoutRecords( + IMARecordScope scope, + String id, + boolean sinceLastFullReport, + IMARecordField columnToOrder, + boolean ascending, + int firstResult, + int maxResults, + String search, + Map searchableColumns) + throws ReportManagerException; + + /** + * Returns a list of all Report Records that are ordered by a column + * and direction (ASC, DESC) that is provided by the user. This method + * helps support the server-side processing in the JQuery DataTables. + * + * @param scope the scope of the search: NONE, ALL, REPORT, or DEVICE + * @param id the id or name of the REPORT or DEVICE to search + * @param sinceLastFullReport + * limits the records to those since the last full report for the device + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @return FilteredRecordsList object with fields for DataTables + * @throws ReportManagerException if unable to create the list + */ + @SuppressWarnings("checkstyle:parameternumber") + FilteredRecordsList getOrderedRecordList( + IMARecordScope scope, + String id, + boolean sinceLastFullReport, + IMARecordField columnToOrder, + boolean ascending, + int firstResult, + int maxResults, + String search) + throws ReportManagerException; + + /** + * Retrieves the Report identified by id. + * + * @param id id of the Report + * @return Report whose name is name + * @throws ReportManagerException if unable to retrieve the Report + */ + Report getReport(UUID id) throws ReportManagerException; + + /** + * Retrieves the Report identified by id. This method + * fully loads a Report object; any lazy fields will be recursively loaded. + * + * @param id id of the Report + * @return Report whose name is name + * @throws ReportManagerException if unable to retrieve the Report + */ + Report getCompleteReport(UUID id) throws ReportManagerException; + + /** + * Updates the contents of the Report. + * + * @param report + * report to be updated + * @throws ReportManagerException + * if any unexpected errors occur while trying to update the report + */ + void updateReport(Report report) throws ReportManagerException; + + /** + * Deletes the Report identified by id. If the + * Report is found and deleted then true is returned, otherwise + * false. + * + * @param id + * id of Report to be deleted + * @return true if successfully found and deleted from repo, otherwise false + * @throws ReportManagerException + * if unable to delete the Report for any reason other than not + * found + */ + boolean deleteReport(UUID id) throws ReportManagerException; +} diff --git a/HIRS_Utils/src/main/java/hirs/persist/ReportManagerException.java b/HIRS_Utils/src/main/java/hirs/persist/ReportManagerException.java index 342396ce6..5ad624eb5 100755 --- a/HIRS_Utils/src/main/java/hirs/persist/ReportManagerException.java +++ b/HIRS_Utils/src/main/java/hirs/persist/ReportManagerException.java @@ -1,45 +1,45 @@ -package hirs.persist; - -/** - * This class represents an Exception generated by a - * ReportyManageer. - */ -public class ReportManagerException extends RuntimeException { - - private static final long serialVersionUID = 3081536085161873284L; - - /** - * Creates a new ReportManagerException that has the message - * msg. - * - * @param msg - * exception message - */ - ReportManagerException(final String msg) { - super(msg); - } - - /** - * Creates a new ReportManagerException that wraps the given - * Throwable. - * - * @param t - * root cause - */ - ReportManagerException(final Throwable t) { - super(t); - } - - /** - * Creates a new ReportManagerException that has the message - * msg and wraps the root cause. - * - * @param msg - * exception message - * @param t - * root cause - */ - ReportManagerException(final String msg, final Throwable t) { - super(msg, t); - } -} +package hirs.persist; + +/** + * This class represents an Exception generated by a + * ReportyManageer. + */ +public class ReportManagerException extends RuntimeException { + + private static final long serialVersionUID = 3081536085161873284L; + + /** + * Creates a new ReportManagerException that has the message + * msg. + * + * @param msg + * exception message + */ + ReportManagerException(final String msg) { + super(msg); + } + + /** + * Creates a new ReportManagerException that wraps the given + * Throwable. + * + * @param t + * root cause + */ + ReportManagerException(final Throwable t) { + super(t); + } + + /** + * Creates a new ReportManagerException that has the message + * msg and wraps the root cause. + * + * @param msg + * exception message + * @param t + * root cause + */ + ReportManagerException(final String msg, final Throwable t) { + super(msg, t); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManager.java b/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManager.java index 6552bc54d..8a46f2b83 100755 --- a/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManager.java +++ b/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManager.java @@ -1,155 +1,155 @@ -package hirs.persist; - -import hirs.FilteredRecordsList; -import hirs.data.persist.ReportSummary; - -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * A ReportSummaryManager manages ReportSummary - * objects. A ReportSummaryManager is used to store and - * manage report summary. It has support for the basic create, read, - * update, and delete methods. - */ -public interface ReportSummaryManager { - - /** - * Stores a new ReportSummary. This stores a new - * ReportSummary to be managed by - * ReportSummaryManager. If ReportSummary - * is successfully saved then a reference to it is - * returned. - * - * @param report Report summary to save - * @return reference to saved ReportSummary - * @throws ReportSummaryManagerException - * if the ReportSummary has previously been saved or unexpected - * error occurs - */ - ReportSummary saveReportSummary(ReportSummary report) throws ReportSummaryManagerException; - - /** - * Updates a ReportSummary. This updates the - * ReportSummary that is managed so subsequent calls to get - * this ReportSum will return the values set by the incoming - * ReportSum. - * - * @param report Report summary - * @throws ReportSummaryManagerException if unable to update the ReportSum - */ - void updateReportSummary(ReportSummary report) throws ReportSummaryManagerException; - - /** - * Returns a list of all ReportSummarys managed by this - * manager. A Class argument may be specified to limit which - * types of ReportSummarys to return. Argument may be null to - * return all ReportSums. - * - * @param clazz class type of ReportSummarys to return (may be null) - * @return list of all managed ReportSummary objects - * @throws ReportSummaryManagerException if unable to create the list - */ - List getReportSummaryList(Class clazz) - throws ReportSummaryManagerException; - - /** - * Returns a list of ReportSummarys of type - * clazz that share the provided hostname. This - * searches through the database for this information. - * - * @param hostname hostname for the machine for which the ReportSummary - * was generated - * @return list of ReportSummarys - * @throws ReportSummaryManagerException if unable to search the database - */ - List getReportSummaryListByHostname(String hostname) - throws ReportSummaryManagerException; - - /** - * Returns a list of all ReportSummary objects that are ordered - * by a column and direction (ASC, DESC) that is provided by the user. This - * method helps support the server-side processing in the JQuery DataTables. - * - * @param columnToOrder Column to be ordered - * @param ascending direction of sort - * @param firstResult starting point of first result in set - * @param maxResults total number we want returned for display in table - * @param search string of criteria to be matched to visible columns - * @param searchableColumns Map of String and boolean values with column - * headers and whether they are to. Boolean is true if field provides - * a typical String that can be searched by Hibernate without - * transformation. - * @param hostname name of the device to filter on - * @return FilteredRecordsList object with fields for DataTables - * @throws ReportSummaryManagerException if unable to create the list - */ - FilteredRecordsList getOrderedReportSummaryList( - String columnToOrder, boolean ascending, int firstResult, - int maxResults, String search, - Map searchableColumns, - String hostname) throws ReportSummaryManagerException; - /** - * Retrieves the ReportSummary identified by id. - * If the ReportSummary cannot be found then null is returned. - * - * @param id id of the ReportSummary - * @return ReportSummary whose name is name or null if not found - * @throws ReportSummaryManagerException if unable to retrieve the ReportSum - */ - ReportSummary getReportSummary(long id) throws ReportSummaryManagerException; - - /** - * Retrieves the ReportSummary identified by the - * Report's id. If the ReportSummary - * cannot be found then null is returned. - * - * @param id - * UUID of the Report - * @return ReportSummary whose Report's - * UUID is id or null if not found - * @throws ReportSummaryManagerException if unable to retrieve the ReportSum - */ - ReportSummary getReportSummaryByReportID(UUID id) throws ReportSummaryManagerException; - - /** - * Deletes the ReportSummary identified by id. - * If the ReportSummary is found and deleted then true is - * returned, otherwise false. - * - * @param id id of ReportSummary to be deleted - * @return true if successfully found and deleted from repo, otherwise false - * @throws ReportSummaryManagerException if unable to delete the ReportSum for any reason other - * than not found - */ - boolean deleteReportSummary(Long id) throws ReportSummaryManagerException; - - /** - * Returns a list of ReportSummarys that contains the latest - * report from each client. This searches through the database for this - * information. - * - * @return list of ReportSummarys - * @throws ReportSummaryManagerException if unable to search the database - */ - List getUniqueClientLatestReportList() throws ReportSummaryManagerException; - - /** - * Retrieves the newest report timestamp for a given hostname. - * - * @param hostname hostname of client to be checked for - * @return newest timestamp from matching ReportSummaries - * @throws ReportSummaryManagerException if unable to return a timestamp - */ - ReportSummary getNewestReport(String hostname) throws ReportSummaryManagerException; - - /** - * Retrieves the first report timestamp for a given hostname. - * - * @param hostname hostname of client to be checked for - * @return newest timestamp from matching ReportSummaries - * @throws ReportSummaryManagerException if unable to search the database - */ - ReportSummary getFirstReport(String hostname) throws ReportSummaryManagerException; -} +package hirs.persist; + +import hirs.FilteredRecordsList; +import hirs.data.persist.ReportSummary; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +/** + * A ReportSummaryManager manages ReportSummary + * objects. A ReportSummaryManager is used to store and + * manage report summary. It has support for the basic create, read, + * update, and delete methods. + */ +public interface ReportSummaryManager { + + /** + * Stores a new ReportSummary. This stores a new + * ReportSummary to be managed by + * ReportSummaryManager. If ReportSummary + * is successfully saved then a reference to it is + * returned. + * + * @param report Report summary to save + * @return reference to saved ReportSummary + * @throws ReportSummaryManagerException + * if the ReportSummary has previously been saved or unexpected + * error occurs + */ + ReportSummary saveReportSummary(ReportSummary report) throws ReportSummaryManagerException; + + /** + * Updates a ReportSummary. This updates the + * ReportSummary that is managed so subsequent calls to get + * this ReportSum will return the values set by the incoming + * ReportSum. + * + * @param report Report summary + * @throws ReportSummaryManagerException if unable to update the ReportSum + */ + void updateReportSummary(ReportSummary report) throws ReportSummaryManagerException; + + /** + * Returns a list of all ReportSummarys managed by this + * manager. A Class argument may be specified to limit which + * types of ReportSummarys to return. Argument may be null to + * return all ReportSums. + * + * @param clazz class type of ReportSummarys to return (may be null) + * @return list of all managed ReportSummary objects + * @throws ReportSummaryManagerException if unable to create the list + */ + List getReportSummaryList(Class clazz) + throws ReportSummaryManagerException; + + /** + * Returns a list of ReportSummarys of type + * clazz that share the provided hostname. This + * searches through the database for this information. + * + * @param hostname hostname for the machine for which the ReportSummary + * was generated + * @return list of ReportSummarys + * @throws ReportSummaryManagerException if unable to search the database + */ + List getReportSummaryListByHostname(String hostname) + throws ReportSummaryManagerException; + + /** + * Returns a list of all ReportSummary objects that are ordered + * by a column and direction (ASC, DESC) that is provided by the user. This + * method helps support the server-side processing in the JQuery DataTables. + * + * @param columnToOrder Column to be ordered + * @param ascending direction of sort + * @param firstResult starting point of first result in set + * @param maxResults total number we want returned for display in table + * @param search string of criteria to be matched to visible columns + * @param searchableColumns Map of String and boolean values with column + * headers and whether they are to. Boolean is true if field provides + * a typical String that can be searched by Hibernate without + * transformation. + * @param hostname name of the device to filter on + * @return FilteredRecordsList object with fields for DataTables + * @throws ReportSummaryManagerException if unable to create the list + */ + FilteredRecordsList getOrderedReportSummaryList( + String columnToOrder, boolean ascending, int firstResult, + int maxResults, String search, + Map searchableColumns, + String hostname) throws ReportSummaryManagerException; + /** + * Retrieves the ReportSummary identified by id. + * If the ReportSummary cannot be found then null is returned. + * + * @param id id of the ReportSummary + * @return ReportSummary whose name is name or null if not found + * @throws ReportSummaryManagerException if unable to retrieve the ReportSum + */ + ReportSummary getReportSummary(long id) throws ReportSummaryManagerException; + + /** + * Retrieves the ReportSummary identified by the + * Report's id. If the ReportSummary + * cannot be found then null is returned. + * + * @param id + * UUID of the Report + * @return ReportSummary whose Report's + * UUID is id or null if not found + * @throws ReportSummaryManagerException if unable to retrieve the ReportSum + */ + ReportSummary getReportSummaryByReportID(UUID id) throws ReportSummaryManagerException; + + /** + * Deletes the ReportSummary identified by id. + * If the ReportSummary is found and deleted then true is + * returned, otherwise false. + * + * @param id id of ReportSummary to be deleted + * @return true if successfully found and deleted from repo, otherwise false + * @throws ReportSummaryManagerException if unable to delete the ReportSum for any reason other + * than not found + */ + boolean deleteReportSummary(Long id) throws ReportSummaryManagerException; + + /** + * Returns a list of ReportSummarys that contains the latest + * report from each client. This searches through the database for this + * information. + * + * @return list of ReportSummarys + * @throws ReportSummaryManagerException if unable to search the database + */ + List getUniqueClientLatestReportList() throws ReportSummaryManagerException; + + /** + * Retrieves the newest report timestamp for a given hostname. + * + * @param hostname hostname of client to be checked for + * @return newest timestamp from matching ReportSummaries + * @throws ReportSummaryManagerException if unable to return a timestamp + */ + ReportSummary getNewestReport(String hostname) throws ReportSummaryManagerException; + + /** + * Retrieves the first report timestamp for a given hostname. + * + * @param hostname hostname of client to be checked for + * @return newest timestamp from matching ReportSummaries + * @throws ReportSummaryManagerException if unable to search the database + */ + ReportSummary getFirstReport(String hostname) throws ReportSummaryManagerException; +} diff --git a/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManagerException.java b/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManagerException.java index 7d2840976..30b077fa0 100755 --- a/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManagerException.java +++ b/HIRS_Utils/src/main/java/hirs/persist/ReportSummaryManagerException.java @@ -1,42 +1,42 @@ -package hirs.persist; - -/** - * This class represents an Exception generated by a - * ReportSumyManageer. - */ -public class ReportSummaryManagerException extends RuntimeException { - - private static final long serialVersionUID = 3081536085161873284L; - - /** - * Creates a new ReportSumMgrException that has the message - * msg. - * @param msg - * exception message - */ - ReportSummaryManagerException(final String msg) { - super(msg); - } - - /** - * Creates a new ReportSumMgrException that wraps the given - * Throwable. - * @param t - * root cause - */ - ReportSummaryManagerException(final Throwable t) { - super(t); - } - - /** - * Creates a new ReportSumMgrException that has the message - * msg and wraps the root cause. - * @param msg - * exception message - * @param t - * root cause - */ - ReportSummaryManagerException(final String msg, final Throwable t) { - super(msg, t); - } -} +package hirs.persist; + +/** + * This class represents an Exception generated by a + * ReportSumyManageer. + */ +public class ReportSummaryManagerException extends RuntimeException { + + private static final long serialVersionUID = 3081536085161873284L; + + /** + * Creates a new ReportSumMgrException that has the message + * msg. + * @param msg + * exception message + */ + ReportSummaryManagerException(final String msg) { + super(msg); + } + + /** + * Creates a new ReportSumMgrException that wraps the given + * Throwable. + * @param t + * root cause + */ + ReportSummaryManagerException(final Throwable t) { + super(t); + } + + /** + * Creates a new ReportSumMgrException that has the message + * msg and wraps the root cause. + * @param msg + * exception message + * @param t + * root cause + */ + ReportSummaryManagerException(final String msg, final Throwable t) { + super(msg, t); + } +} diff --git a/HIRS_Utils/src/main/java/hirs/tpm/TPMBaselineGeneratorException.java b/HIRS_Utils/src/main/java/hirs/tpm/TPMBaselineGeneratorException.java index 42462f762..e8c742cb9 100644 --- a/HIRS_Utils/src/main/java/hirs/tpm/TPMBaselineGeneratorException.java +++ b/HIRS_Utils/src/main/java/hirs/tpm/TPMBaselineGeneratorException.java @@ -1,46 +1,46 @@ -package hirs.tpm; - -/** - * This class represents an Exception generated by - * CreateTPMBaseline. - */ -public class TPMBaselineGeneratorException extends Exception { - - private static final long serialVersionUID = 8850867303391694668L; - - /** - * Creates a new CreateTPMBaselineException that has the - * message msg. - * - * @param msg - * exception message - */ - TPMBaselineGeneratorException(final String msg) { - super(msg); - } - - /** - * Creates a new CreateTPMBaselineException that wraps the - * given Throwable. - * - * @param t - * root cause - */ - TPMBaselineGeneratorException(final Throwable t) { - super(t); - } - - /** - * Creates a new CreateTPMBaselineException that has the - * message msg and wraps the root cause. - * - * @param msg - * exception message - * @param t - * root cause - */ - TPMBaselineGeneratorException(final String msg, final Throwable t) { - super(msg, t); - } - -} +package hirs.tpm; + +/** + * This class represents an Exception generated by + * CreateTPMBaseline. + */ +public class TPMBaselineGeneratorException extends Exception { + + private static final long serialVersionUID = 8850867303391694668L; + + /** + * Creates a new CreateTPMBaselineException that has the + * message msg. + * + * @param msg + * exception message + */ + TPMBaselineGeneratorException(final String msg) { + super(msg); + } + + /** + * Creates a new CreateTPMBaselineException that wraps the + * given Throwable. + * + * @param t + * root cause + */ + TPMBaselineGeneratorException(final Throwable t) { + super(t); + } + + /** + * Creates a new CreateTPMBaselineException that has the + * message msg and wraps the root cause. + * + * @param msg + * exception message + * @param t + * root cause + */ + TPMBaselineGeneratorException(final String msg, final Throwable t) { + super(msg, t); + } + +} diff --git a/HIRS_Utils/src/test/java/hirs/DeviceGroupSerializerTest.java b/HIRS_Utils/src/test/java/hirs/DeviceGroupSerializerTest.java index 6c335f36b..05fe07ea4 100644 --- a/HIRS_Utils/src/test/java/hirs/DeviceGroupSerializerTest.java +++ b/HIRS_Utils/src/test/java/hirs/DeviceGroupSerializerTest.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.joda.JodaModule; import hirs.data.persist.AppraisalStatus; import hirs.data.persist.Device; import hirs.data.persist.DeviceGroup; @@ -28,9 +29,9 @@ */ public class DeviceGroupSerializerTest { - private static final int COUNT_OF_ID_FIELD_OUTSIDE_DEVICE_GROUP = 2; + private static final int COUNT_OF_ID_FIELD_OUTSIDE_DEVICE_GROUP = 1; private static final int COUNT_OF_CREATION_DATE_FIELD_OUTSIDE_DEVICE_GROUP = 1; - private static final int COUNT_OF_NAME_FIELD_OUTSIDE_DEVICE_GROUP = 45; + private static final int COUNT_OF_NAME_FIELD_OUTSIDE_DEVICE_GROUP = 1; private static final int COUNT_OF_HEALTH_STATUS_FIELD_OUTSIDE_DEVICE_GROUP = 1; /** @@ -116,7 +117,8 @@ private void assertDeviceSerializedCorrectly(final Device testDevice) { private void assertDevicesSerializedCorrectly(final List testDevices) { String serializedDevices = null; try { - serializedDevices = new ObjectMapper().writeValueAsString(testDevices); + serializedDevices = new ObjectMapper().registerModule( + new JodaModule()).writeValueAsString(testDevices); } catch (JsonProcessingException jpe) { Assert.fail("Failed to successfully serialize the Test Devices"); } diff --git a/TPM_Utils/build.gradle b/TPM_Utils/build.gradle index ba9247316..6368b832e 100644 --- a/TPM_Utils/build.gradle +++ b/TPM_Utils/build.gradle @@ -18,7 +18,7 @@ ext.configDir = new File(projectDir, 'config') ext.checkstyleConfigDir = "$configDir/checkstyle" checkstyle { - toolVersion = '5.7' + toolVersion = '8.45.1' configFile = checkstyleConfigFile configProperties.put('basedir', checkstyleConfigDir) ignoreFailures = false diff --git a/build.gradle b/build.gradle index 6cfdcdb32..f9bacdeb6 100644 --- a/build.gradle +++ b/build.gradle @@ -91,7 +91,7 @@ subprojects { // here to ensure that all projects are using the same versions of common // dependencies: ext.libs = [ - bouncy_castle: 'org.bouncycastle:bcmail-jdk15on:1.59', + bouncy_castle: 'org.bouncycastle:bcmail-jdk15on:1.67', checkstyle: 'com.puppycrawl.tools:checkstyle:8.45.1', commons_cli: 'commons-cli:commons-cli:1.4', commons_codec: 'commons-codec:commons-codec:1.9', @@ -103,7 +103,7 @@ subprojects { commons_upload:'commons-fileupload:commons-fileupload:1.3.1', commons_valid: 'commons-validator:commons-validator:1.4.0', findbugs: 'com.google.code.findbugs:findbugs:3.0.0', - gson: 'com.google.code.gson:gson:2.2.4', + gson: 'com.google.code.gson:gson:2.10.1', guava: 'com.google.guava:guava:32.0.1-jre', hibernate: [ 'org.hibernate.common:hibernate-commons-annotations:4.0.4.Final', 'org.hibernate:hibernate-core:4.3.11.Final', @@ -111,9 +111,10 @@ subprojects { hikari: 'com.zaxxer:HikariCP:2.4.1', hsqldb: 'org.hsqldb:hsqldb:2.3.2', http: 'org.apache.httpcomponents:httpclient:4.5', - jackson: [ 'com.fasterxml.jackson.core:jackson-core:2.6.3', - 'com.fasterxml.jackson.core:jackson-databind:2.6.3', - 'com.fasterxml.jackson.core:jackson-annotations:2.6.3'], + jackson: [ 'com.fasterxml.jackson.core:jackson-core:2.15.2', + 'com.fasterxml.jackson.core:jackson-databind:2.15.2', + 'com.fasterxml.jackson.core:jackson-annotations:2.15.2', + 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.15.2'], jadira_usertype: 'org.jadira.usertype:usertype.core:4.0.0.GA', jcommander: 'com.beust:jcommander:1.72', joda_time: 'joda-time:joda-time:2.9.4', diff --git a/tools/tcg_eventlog_tool/build.gradle b/tools/tcg_eventlog_tool/build.gradle index ddfbc1103..328ef2fe4 100644 --- a/tools/tcg_eventlog_tool/build.gradle +++ b/tools/tcg_eventlog_tool/build.gradle @@ -21,7 +21,7 @@ dependencies { ext.configDir = new File(projectDir, 'config') ext.checkstyleConfigDir = "$configDir/checkstyle" checkstyle { - toolVersion = '5.7' + toolVersion = '8.45.1' configFile = checkstyleConfigFile configProperties.put('basedir', checkstyleConfigDir) ignoreFailures = false