updated some more and removed managers

This commit is contained in:
Cyrus 2022-11-18 16:04:57 -05:00
parent 7859ee213a
commit f5a6eccd6f
6 changed files with 2 additions and 769 deletions

View File

@ -1,4 +1,4 @@
package hirs.attestationca.portal;
package hirs.attestationca;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;

View File

@ -1,8 +1,8 @@
package hirs.attestationca.entity;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import hirs.AppraisalResultSerializer;
import hirs.appraiser.Appraiser;
import hirs.attestationca.AppraisalResultSerializer;
import hirs.data.persist.AbstractEntity;
import hirs.data.persist.AppraisalStatus;

View File

@ -1,312 +0,0 @@
package hirs.attestationca.servicemanager;
import hirs.FilteredRecordsList;
import hirs.attestationca.entity.Device;
import hirs.persist.CriteriaModifier;
import hirs.persist.DBManagerException;
import hirs.persist.DeviceManagerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This class defines a <code>DeviceManager</code> that stores the devices
* in a database.
*/
@Service
public class DBDeviceManager extends DBManager<Device> implements
DeviceManager {
private static final Logger LOGGER = LogManager.getLogger();
/**
* Creates a new <code>DBDeviceManager</code> that uses the default
* database. The default database is used to store all of the
* <code>Device</code>s.
*
* @param em entity manager used to access database connections
*/
public DBDeviceManager(final EntityManager em) {
super(Device.class, em);
}
/**
* Saves the <code>Device</code> in the database. This creates a new
* database session and saves the device. If the <code>Device</code> had
* previously been saved then a <code>DeviceManagerException</code> is
* thrown.
*
* @param device
* device to save
* @return reference to saved device
* @throws hirs.persist.DeviceManagerException
* if device has previously been saved or an error occurs
* while trying to save it to the database
*/
@Override
public final Device saveDevice(final Device device)
throws DeviceManagerException {
LOGGER.debug("saving device: {}", device);
try {
return super.save(device);
} catch (DBManagerException e) {
throw new DeviceManagerException(e);
}
}
/**
* Updates a <code>Device</code>. This updates the database entries to
* reflect the new values that should be set.
*
* @param device
* device
* @throws DeviceManagerException
* if device has not previously been saved or an error occurs
* while trying to save it to the database
*/
@Override
public final void updateDevice(final Device device)
throws DeviceManagerException {
LOGGER.debug("updating device: {}", device);
try {
super.update(device);
} catch (DBManagerException e) {
throw new DeviceManagerException(e);
}
}
/**
* Updates list of <code>Device</code>s. This updates the database entries
* to reflect the new values that should be set. Commonly used when
* deleting a DeviceGroup.
*
* @param deviceList
* list of devices that should be updated in single transaction
* @throws DeviceManagerException
* if device has not previously been saved or an error occurs
* while trying to save it to the database
*/
@Override
public final void updateDeviceList(final Set<Device> deviceList)
throws DeviceManagerException {
LOGGER.debug("updating all devices in list");
Session session = getSession();
Transaction tx = session.beginTransaction();
try {
for (final Device device : deviceList) {
session.merge(device);
}
session.getTransaction().commit();
} catch (Exception e) {
final String msg = "unable to update all devices in list";
LOGGER.error(msg, e);
LOGGER.debug("rolling back transaction");
tx.rollback();
throw new DBManagerException(msg, e);
}
}
/**
* Returns a list of all <code>Devices</code>. This searches through
* the database for this information.
*
* @return list of <code>Devices</code>
* @throws DeviceManagerException
* if unable to search the database
*/
@Override
public final Set<Device> getDeviceList() throws DeviceManagerException {
LOGGER.debug("getting device list");
try {
final List<Device> devices = super.getList(Device.class);
return new HashSet<>(devices);
} catch (DBManagerException e) {
throw new DeviceManagerException(e);
}
}
/**
* Returns a list of all <code>Device</code> names. This searches through
* the database for this information.
*
* @return list of <code>Device</code> names
* @throws DeviceManagerException
* if unable to search the database
*/
@Override
public final List<String> getDeviceNameList()
throws DeviceManagerException {
LOGGER.debug("getting device list");
List<String> deviceNames = new LinkedList<>();
try {
final List<Device> devices = super.getList(Device.class);
for (Device b : devices) {
deviceNames.add(b.getName());
}
} catch (DBManagerException e) {
throw new DeviceManagerException(e);
}
return deviceNames;
}
/**
* Returns a list of all <code>Device</code>s 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
*
* @return FilteredRecordsList object with fields for DataTables
* @throws DeviceManagerException
* if unable to create the list
*/
@Override
public final FilteredRecordsList<Device> getOrderedDeviceList(
final String columnToOrder, final boolean ascending, final int firstResult,
final int maxResults, final String search)
throws DeviceManagerException {
if (columnToOrder == null) {
LOGGER.debug("null object argument");
throw new NullPointerException("object");
}
//Maps object types and their ability to be searched by Hibernate
//without modification
Map<String, Boolean> searchableColumns = new HashMap<>();
searchableColumns.put("name", true);
searchableColumns.put("group.name", true);
searchableColumns.put("last_report_timestamp", false);
CriteriaModifier modifier = new CriteriaModifier() {
@Override
public void modify(final Criteria criteria) {
criteria.createAlias("deviceGroup", "group");
}
};
try {
LOGGER.debug("Getting baseline list");
return super.getOrderedList(Device.class, columnToOrder, ascending, firstResult,
maxResults, search, searchableColumns, modifier);
} catch (DBManagerException e) {
LOGGER.error(e);
return null;
}
}
/**
* Retrieves the <code>Device</code> from the database. This searches the
* database for an entry whose name matches <code>name</code>. It then
* reconstructs a <code>Device</code> object from the database entry
*
* @param name
* name of the device
* @return device if found, otherwise null.
* @throws DeviceManagerException
* if unable to search the database or recreate the
* <code>Device</code>
*/
@Override
public final Device getDevice(final String name)
throws DeviceManagerException {
LOGGER.debug("getting device: {}", name);
try {
return super.get(name);
} catch (DBManagerException e) {
throw new DeviceManagerException(e);
}
}
/**
* Used to produce a list of all <code>Device</code>s associated with the Default Group.
*
* @return list of Devices that are part of the Default Group
* @throws DeviceManagerException
* if unable to find the device or delete it from the database
*/
@Override
public final List<Device> getDefaultDevices() throws DeviceManagerException {
Transaction tx = null;
Session session = getSession();
List<Device> devices = new ArrayList<>();
try {
LOGGER.debug("retrieving defaults devices from db");
tx = session.beginTransaction();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Device> criteriaQuery = criteriaBuilder.createQuery(Device.class);
Root<Device> root = criteriaQuery.from(Device.class);
root.join("group.name", JoinType.LEFT).alias("group");
Predicate recordPredicate = criteriaBuilder
.and(criteriaBuilder.equal(root.get("group.name"), "Default Group"));
criteriaQuery.select(root).where(recordPredicate).distinct(true);
Query<Device> query = session.createQuery(criteriaQuery);
List<Device> results = query.getResultList();
if (results != null) {
devices.addAll(results);
}
// List list = session.createCriteria(Device.class).createAlias("deviceGroup", "group")
// .add(Restrictions.eq("group.name", DeviceGroup.DEFAULT_GROUP))
// .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
// .list();
tx.commit();
} catch (HibernateException e) {
final String msg = "unable to retrieve default devices";
LOGGER.error(msg, e);
if (tx != null) {
LOGGER.debug("rolling back transaction");
tx.rollback();
}
throw e;
}
return devices;
}
/**
* Deletes the <code>Device</code> from the database. This removes all
* of the database entries that stored information with regards to the
* <code>Device</code> with a foreign key relationship.
*
* @param name of the device to be deleted
* @return true if successfully found and deleted, false if otherwise
*/
@Override
public final boolean deleteDevice(final String name)
throws DeviceManagerException {
LOGGER.debug("deleting device: {}", name);
try {
return super.delete(name);
} catch (DBManagerException e) {
throw new DeviceManagerException(e);
}
}
}

View File

@ -1,159 +0,0 @@
package hirs.attestationca.servicemanager;
import hirs.data.persist.enums.PortalScheme;
import hirs.data.persist.info.PortalInfo;
import hirs.persist.DBManagerException;
import hirs.persist.PortalInfoManagerException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import java.net.URI;
import java.net.URISyntaxException;
/**
* A <code>DBPortalInfoManager</code> is a service (extends <code>DBManager</code>) that
* implements the <code>PortalInfoManager</code> that stores and retrieves Portal Info objects.
*/
@Service
public class DBPortalInfoManager extends DBManager<PortalInfo> implements PortalInfoManager {
private static final Logger LOGGER = LogManager.getLogger(DBPortalInfoManager.class);
/**
* Creates a new <code>DBPortalInfoManager</code>. The optional SessionFactory parameter is
* used to manage sessions with a hibernate db.
*
* @param em a hibernate session
*/
public DBPortalInfoManager(final EntityManager em) {
super(PortalInfo.class, em);
}
/**
* Saves the <code>PortalInfo</code> in the database. This creates a new database
* session and saves the PortalInfo. If the <code>PortalInfo</code> had previously
* been saved then a <code>PortalInfoManagerException</code> is thrown.
*
* @param info PortalInfo to save
* @return reference to saved PortalInfo
* @throws hirs.persist.PortalInfoManagerException if PortalInfo has previously been saved or an
* error occurs while trying to save it to the database
*/
@Override
public final PortalInfo savePortalInfo(final PortalInfo info)
throws PortalInfoManagerException {
LOGGER.debug("saving Portal Info {}", info);
try {
return super.save(info);
} catch (DBManagerException e) {
throw new PortalInfoManagerException(e);
}
}
/**
* Updates a <code>PortalInfo</code>. This updates the database entries to reflect the new
* values that should be set.
*
* @param info PortalInfo
* @throws PortalInfoManagerException if PortalInfo has not previously been saved or
* an error occurs while trying to save it to the database
*/
@Override
public final void updatePortalInfo(final PortalInfo info)
throws PortalInfoManagerException {
LOGGER.debug("updating Portal Info: {}", info);
try {
super.update(info);
} catch (DBManagerException e) {
throw new PortalInfoManagerException(e);
}
}
/**
* Retrieves the <code>PortalInfo</code> from the database. This searches the database for an
* entry whose name matches <code>name</code>. It then reconstructs a <code>PortalInfo</code>
* object from the database entry.
*
* @param scheme PortalInfo.Scheme of the PortalInfo
* @return PortalInfo if found, otherwise null.
* @throws PortalInfoManagerException if unable to search the database or recreate the
* <code>PortalInfo</code>
*/
@Override
public final PortalInfo getPortalInfo(final PortalScheme scheme)
throws PortalInfoManagerException {
LOGGER.debug("getting Portal Info: {}", scheme.name());
try {
return super.get(scheme.name());
} catch (DBManagerException e) {
throw new PortalInfoManagerException(e);
}
}
/**
* Deletes the <code>PortalInfo</code> from the database. This removes all of the database
* entries that stored information with regards to the this <code>PortalInfo</code>.
* Currently, iterates over <code>Policy</code> entries and removes the selected
* <code>PortalInfo</code> from them if it exists. This needs to be fixed as this should not
* be performed without user action. Update is expected soon.
*
* @param scheme PortalInfo.Scheme of the <code>PortalInfo</code> to delete
* @return true if successfully found and deleted <code>PortalInfo</code>
* @throws PortalInfoManagerException if unable to find the PortalInfo or delete it
* from the database
*/
@Override
public final boolean deletePortalInfo(final PortalScheme scheme)
throws PortalInfoManagerException {
LOGGER.debug("deleting Portal Info: {}", scheme.name());
try {
return super.delete(scheme.name());
} catch (DBManagerException e) {
throw new PortalInfoManagerException(e);
}
}
/**
* Retrieve the <code>PortalInfo</code> object stored into the repo
* and return the url it represents.
*
* @return the URL represented by the <code>PortalInfo</code> object.
*/
@Override
public final String getPortalUrlBase() {
PortalInfo info;
try {
// Prefer HIRS to use HTTPS, but check HTTP if needed
info = getPortalInfo(PortalScheme.HTTPS);
if (info == null) {
info = getPortalInfo(PortalScheme.HTTP);
}
} catch (Exception e) {
info = null;
}
// The default base url
String url = "Your_HIRS_Portal/";
try {
if (info != null && info.getIpAddress() != null) {
String context = "/";
if (info.getContextName() != null) {
context += info.getContextName() + "/";
}
URI uri = new URI(info.getSchemeName().toLowerCase(), null,
info.getIpAddress().getHostName(), info.getPort(),
context, null, null);
url = uri.toString();
}
} catch (URISyntaxException e) {
LOGGER.error("DBPortalInfoManager.getPortalUrlBase():"
+ " Could not create the URI. Returning the default.");
}
return url;
}
}

View File

@ -1,195 +0,0 @@
package hirs.attestationca.servicemanager;
import hirs.data.persist.Report;
import hirs.persist.DBManagerException;
import hirs.persist.ReportManagerException;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.Logger;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
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 <code>ReportManager</code> that stores the reports in a
* database.
*/
@Service
public class DBReportManager extends DBManager<Report> implements ReportManager {
private static final Logger LOGGER = getLogger(DBReportManager.class);
/**
* Creates a new <code>DBReportManager</code> that uses the provided sessionFactory
* to interact with a database.
*
* @param em entity manager used to access database connections
*/
public DBReportManager(final EntityManager em) {
super(Report.class, em);
}
/**
* Saves the <code>Report</code> in the database and returns it.
*
* @param report
* report to save
* @return <code>Report</code> that was saved
* @throws hirs.persist.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 <code>Report</code>s of type <code>clazz</code>.
* 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 <code>Report</code>s to return (may be null)
* @return list of <code>Report</code>s
* @throws ReportManagerException
* if unable to search the database
*/
@Override
public final List<Report> getReportList(final Class<?
extends Report> clazz)
throws ReportManagerException {
LOGGER.debug("getting report list");
try {
//super.getList(Report);
return null;
} catch (DBManagerException e) {
throw new ReportManagerException(e);
}
}
/**
* Retrieves the <code>Report</code> from the database. This searches the
* database for an entry whose id matches <code>id</code>. It then
* reconstructs a <code>Report</code> object from the database entry.
*
* Note: <code>IMAMeasurementRecords</code> 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 <code>Report</code>
*/
@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 <code>Report</code>. 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 <code>Report</code> from the database. This removes all of
* the database entries that stored information with regards to the this
* <code>Report</code>.
* <p>
* If the <code>Report</code> is referenced by any other tables then this
* will throw a <code>ReportManagerException</code>.
*
* @param id
* id of the <code>Report</code> to delete
* @return true if successfully found and deleted the <code>Report</code>
* @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 false; //super.delete(id);
} catch (DBManagerException e) {
throw new ReportManagerException(e);
}
}
private Conjunction buildImaRecordSearchFilter(final String search, final
Map<String, Boolean> 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<String, Boolean> 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;
}
}

View File

@ -1,101 +0,0 @@
package hirs.attestationca.servicemanager;
import hirs.attestationca.entity.Device;
import hirs.attestationca.entity.ReportRequestState;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* This class defines a <code>ReportRequestStateManager</code> that stores ReportRequestStates in a
* database.
*/
@Service
public class DBReportRequestStateManager extends DBManager<ReportRequestState>
implements ReportRequestStateManager {
private static final Logger LOGGER = LogManager.getLogger(DBReportRequestStateManager.class);
/**
* Creates a new <code>DBReportRequestStateManager</code> that uses the default database. The
* default database is used to store all of the <code>ReportRequestState</code>s.
*
* @param em entity manager used to access database connections
*/
public DBReportRequestStateManager(final EntityManager em) {
super(ReportRequestState.class, em);
}
/**
* Retrieves the state of a device, if the device and state exists.
*
* @param device the Device whose state should be retrieved
* @return the associated ReportRequestState, or null if no associated state was found
*/
@Override
public final ReportRequestState getState(final Device device) {
CriteriaBuilder builder = this.getSession().getCriteriaBuilder();
Root<ReportRequestState> root = builder.createQuery(ReportRequestState.class)
.from(ReportRequestState.class);
Predicate predicate = builder.equal(root.get("device"), device);
List<ReportRequestState> results = getWithCriteria(Collections.singletonList(predicate));
if (results.isEmpty()) {
return null;
} else {
LOGGER.debug("Retrieved ReportRequestState: {}", results.get(0));
return results.get(0);
}
}
/**
* Return a Collection of all persisted ReportRequestStates in the database.
*
* @return the Collection of all persisted ReportRequestStates
*/
@Override
public final List<ReportRequestState> getLateDeviceStates() {
CriteriaBuilder builder = this.getSession().getCriteriaBuilder();
Root<ReportRequestState> root = builder.createQuery(ReportRequestState.class)
.from(ReportRequestState.class);
Predicate predicate = builder.lessThanOrEqualTo(root.get("dueDate"), new Date());
return getWithCriteria(Collections.singletonList(predicate));
}
/**
* Saves the given state to the database. The associated Device must be saved prior to saving
* the state.
*
* @param state the state to save
* @return the saved copy of the state
*/
@Override
public final ReportRequestState saveState(final ReportRequestState state) {
if (state.getId() == null) {
return save(state);
} else {
update(state);
ReportRequestState updatedState = getState(state.getDevice());
LOGGER.debug("Updated ReportRequestState: {}", updatedState);
return updatedState;
}
}
/**
* Deletes the given {@link ReportRequestState} from the database.
*
* @param state the ReportRequestState instance to delete
*/
@Override
public final void deleteState(final ReportRequestState state) {
delete(state.toString()); // cyrus-dev
}
}