Author: [log in to unmask] Date: Thu Apr 2 18:14:47 2015 New Revision: 2660 Log: Apply changes from CheckStyle warnings. Added: java/trunk/conditions/src/main/java/org/hps/conditions/api/BaseConditionsObject.java - copied, changed from r2659, java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObject.java java/trunk/conditions/src/main/java/org/hps/conditions/api/BaseConditionsObjectCollection.java - copied, changed from r2653, java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObjectCollection.java java/trunk/conditions/src/main/java/org/hps/conditions/api/package-info.java java/trunk/conditions/src/main/java/org/hps/conditions/beam/package-info.java java/trunk/conditions/src/main/java/org/hps/conditions/cli/package-info.java java/trunk/conditions/src/main/java/org/hps/conditions/database/AbstractConditionsObjectConverter.java - copied, changed from r2659, java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsObjectConverter.java java/trunk/conditions/src/main/java/org/hps/conditions/database/package-info.java Removed: java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObject.java java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObjectCollection.java java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsObjectConverter.java Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ConditionsDriver.java java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractIdentifier.java java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObject.java java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectCollection.java java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectException.java java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectUtilities.java java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsRecord.java java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsSeries.java java/trunk/conditions/src/main/java/org/hps/conditions/api/FieldValueMap.java java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamConditions.java java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamCurrent.java java/trunk/conditions/src/main/java/org/hps/conditions/beam/ImportBeamConditionsEngRun.java java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java java/trunk/conditions/src/main/java/org/hps/conditions/cli/AddCommand.java java/trunk/conditions/src/main/java/org/hps/conditions/cli/CommandLineTool.java java/trunk/conditions/src/main/java/org/hps/conditions/cli/LoadCommand.java java/trunk/conditions/src/main/java/org/hps/conditions/cli/PrintCommand.java java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsRecordConverter.java java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsSeriesConverter.java java/trunk/conditions/src/main/java/org/hps/conditions/database/ConnectionParameters.java java/trunk/conditions/src/main/java/org/hps/conditions/database/Converter.java java/trunk/conditions/src/main/java/org/hps/conditions/database/ConverterRegistry.java java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseConditionsManager.java java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseUtilities.java java/trunk/conditions/src/main/java/org/hps/conditions/database/Field.java java/trunk/conditions/src/main/java/org/hps/conditions/database/MultipleCollectionsAction.java java/trunk/conditions/src/main/java/org/hps/conditions/database/QueryBuilder.java java/trunk/conditions/src/main/java/org/hps/conditions/database/Table.java java/trunk/conditions/src/main/java/org/hps/conditions/database/TableMetaData.java java/trunk/conditions/src/main/java/org/hps/conditions/database/TableRegistry.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalBadChannel.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCalibration.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannel.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannelConstants.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditions.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsConverter.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsUtil.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCrystalChannelMap.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalGain.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLed.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLedCalibration.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalTimeShift.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/TestRunEcalConditionsConverter.java java/trunk/conditions/src/main/java/org/hps/conditions/ecal/package-info.java java/trunk/conditions/src/main/java/org/hps/conditions/package-info.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtChannel.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtConditions.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtDaqMapping.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtT0Shift.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtAlignmentConstant.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtBadChannel.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtCalibration.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConditionsLoader.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConfiguration.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtGain.java java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtShapeFitParameters.java java/trunk/conditions/src/test/java/org/hps/conditions/EngRunConditionsTest.java Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ConditionsDriver.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ConditionsDriver.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ConditionsDriver.java Thu Apr 2 18:14:47 2015 @@ -6,13 +6,11 @@ /** * <p> - * This {@link org.lcsim.util.Driver} can be used to customize the behavior - * of the {@link DatabaseConditionsManager}. It allows the setting of a - * detector name and run number, as well as other parameters, if the user - * wishes to override the default behavior of the conditions system, which - * is generally activated from LCSim events. It is not necessary to run this - * Driver in order to activate the default database conditions system. Only - * one instance of this Driver should ever be included in a steering file. + * This {@link org.lcsim.util.Driver} can be used to customize the behavior of the {@link DatabaseConditionsManager}. It + * allows the setting of a detector name and run number, as well as other parameters, if the user wishes to override the + * default behavior of the conditions system, which is generally activated from LCSim events. It is not necessary to run + * this Driver in order to activate the default database conditions system. Only one instance of this Driver should ever + * be included in a steering file. * <p> * This is an example of using the Driver in an XML steering file: * <pre> @@ -25,89 +23,97 @@ * <freeze>true</freeze> * </driver> * } - * </pre> + * </pre> * <p> - * This is a "special" Driver which must have its initialization occur at the right time. - * It has a custom initialization method {@link #initialize()} which should be called after - * all Driver setup has occurred, but before the job actually begins. This is so the conditions - * system functions properly, including the activation of registered listeners. The setup is - * performed by in the class {@link org.hps.job.JobManager}, which is used in the - * default command line front end of the hps-distribution. If that class is not being used, then - * the method must be executed manually at the right time to achieve the proper behavior. + * This is a "special" Driver which must have its initialization occur at the right time. It has a custom initialization + * method {@link #initialize()} which should be called after all Driver setup has occurred, but before the job actually + * begins. This is so the conditions system functions properly, including the activation of registered listeners. The + * setup is performed by in the class {@link org.hps.job.JobManager}, which is used in the default command line front + * end of the hps-distribution. If that class is not being used, then the method must be executed manually at the right + * time to achieve the proper behavior. * - * @author Jeremy McCormick <[log in to unmask]> + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public class ConditionsDriver extends Driver { - String detectorName = null; - String tag = null; - String xmlConfigResource = null; - int runNumber = 0; - boolean freeze; - + /** The name of the detector model. */ + private String detectorName; + + /** The conditions system tag. */ + private String tag; + + /** The XML config resource. */ + private String xmlConfigResource; + + /** The user run number. */ + private int runNumber = 0; + + /** + * True to freeze the conditions system after activation (requires valid detector name and run number). + */ + private boolean freeze; + /** * Default constructor. */ public ConditionsDriver() { } - + /** * Set the name of the detector to use. * @param detectorName The name of the detector. */ - public void setDetectorName(String detectorName) { + public final void setDetectorName(final String detectorName) { this.detectorName = detectorName; } - + /** - * Set whether or not the conditions system should be "frozen" after the - * detector name and run number are set. When frozen, the conditions system - * will ignore subsequent calls to {@link org.lcsim.conditions.ConditionsManager#setDetector(String, int)} - * and instead use the user supplied detector and run for the whole job. + * Set whether or not the conditions system should be "frozen" after the detector name and run number are set. When + * frozen, the conditions system will ignore subsequent calls to + * {@link org.lcsim.conditions.ConditionsManager#setDetector(String, int)} and instead use the user supplied + * detector and run for the whole job. * @param freeze True to freeze the conditions system after it is setup. */ - public void setFreeze(boolean freeze) { + public final void setFreeze(final boolean freeze) { this.freeze = freeze; } - + /** - * Set a custom run number to setup the conditions system. - * In the case where the actual event stream has run numbers that differ from this one, - * most likely the Driver should be configured to be frozen after setup using - * {@link #setFreeze(boolean)}. - * - * The method {@link #setDetectorName(String)} needs to be called before this one - * or an exception will be thrown. + * Set a custom run number to setup the conditions system. In the case where the actual event stream has run numbers + * that differ from this one, most likely the Driver should be configured to be frozen after setup using + * {@link #setFreeze(boolean)}. + * + * The method {@link #setDetectorName(String)} needs to be called before this one or an exception will be thrown. * @param runNumber The user supplied run number for the job. */ - public void setRunNumber(int runNumber) { + public final void setRunNumber(final int runNumber) { this.runNumber = runNumber; - } - + } + /** * Set a tag used to filter ConditionsRecords. * @param tag The tag value e.g. "eng_run" etc. */ - public void setTag(String tag) { + public final void setTag(final String tag) { this.tag = tag; } - + /** * Set an XML configuration resource. * @param xmlConfigResource The XML configuration resource. */ - public void setXmlConfigResource(String xmlConfigResource) { + public final void setXmlConfigResource(final String xmlConfigResource) { this.xmlConfigResource = xmlConfigResource; } - + /** * Setup the conditions system based on the Driver parameters. * @throws RuntimeException If there is a problem setting up the conditions system. */ - public void initialize() { - - DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); - + public final void initialize() { + + final DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); + if (xmlConfigResource != null) { // Set a custom XML configuration resource. conditionsManager.setXmlConfig(xmlConfigResource); Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractIdentifier.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractIdentifier.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractIdentifier.java Thu Apr 2 18:14:47 2015 @@ -3,20 +3,21 @@ /** * This class is a simplistic representation of a packaged identifier for use in * the conditions system. - * - * @author Jeremy McCormick <[log in to unmask]> - * + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public abstract class AbstractIdentifier { /** * Encode the ID into a long. + * * @return The ID encoded into a long. */ public abstract long encode(); /** * Check if the ID is valid. + * * @return True if valid. */ public abstract boolean isValid(); Copied: java/trunk/conditions/src/main/java/org/hps/conditions/api/BaseConditionsObject.java (from r2659, java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObject.java) ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObject.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/BaseConditionsObject.java Thu Apr 2 18:14:47 2015 @@ -3,60 +3,138 @@ import java.util.Map.Entry; /** - * The abstract implementation of {@link ConditionsObject}. - * @author Jeremy McCormick <[log in to unmask]> + * The basic implementation of {@link ConditionsObject}. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -public abstract class AbstractConditionsObject implements ConditionsObject { +public class BaseConditionsObject implements ConditionsObject { - protected int rowId = -1; - protected FieldValueMap fieldValues; + /** + * The database row ID. + */ + private int rowID = -1; - /** + /** + * The map of field-value pairs. + */ + private FieldValueMap fieldValues; + + /** * Constructor for sub-classing. */ - protected AbstractConditionsObject() { + protected BaseConditionsObject() { fieldValues = new FieldValueMap(); } - public int getRowId() { - return rowId; + /** + * Get the row ID of this object. + * <p> + * Implements {@link ConditionsObject#getRowId()}. + * + * @return The row ID. + */ + @Override + public final int getRowId() { + return rowID; } - public boolean isNew() { - return rowId == -1; + /** + * True if object is new e.g. not in the database. + * <p> + * Implements {@link ConditionsObject#isNew()}. + * + * @return True if object is new. + */ + @Override + public final boolean isNew() { + return rowID == -1; } - - public void setFieldValue(String key, Object value) { + /** + * Set the value of a field. + * <p> + * Implements {@link ConditionsObject#setFieldValue(String, Object)}. + * + * @param key The name of the field. + * @param value The value of the field. + */ + @Override + public final void setFieldValue(final String key, final Object value) { fieldValues.put(key, value); } - public void setFieldValues(FieldValueMap fieldValues) { + /** + * Set all field values using a {@link FieldValueMap}. + * <p> + * Implements {@link ConditionsObject#setFieldValues(FieldValueMap)}. + * + * @param fieldValues The list of key-value pairs. + */ + @Override + public final void setFieldValues(final FieldValueMap fieldValues) { this.fieldValues = fieldValues; } - public <T> T getFieldValue(Class<T> klass, String field) { + /** + * Get the value of a field. + * <p> + * Implements {@link ConditionsObject#getFieldValue(Class, String)}. + * + * @param klass The inferred return type. + * @param field The name of the field. + * @param <T> The generic type for inferrence of return type. + * @return The value of the field. + */ + @Override + public final <T> T getFieldValue(final Class<T> klass, final String field) { return klass.cast(fieldValues.get(field)); } - - public FieldValueMap getFieldValues() { + + /** + * Get the field-value map. + * <p> + * Implements {@link ConditionsObject#getFieldValues()}. + * + * @return The field-value map. + */ + @Override + public final FieldValueMap getFieldValues() { return this.fieldValues; } + /** + * Get a field value. + * + * @param field The field name. + * @param <T> The type inferred from the assigned variable. + * @return The field value. + */ @SuppressWarnings("unchecked") - public <T> T getFieldValue(String field) { + public final <T> T getFieldValue(final String field) { return (T) fieldValues.get(field); } - public void setRowId(int rowId) throws ConditionsObjectException { + /** + * Set the database row ID of the object. + * + * @param rowId The database row ID. + * @throws ConditionsObjectException If the object already has a row ID. + */ + public final void setRowID(final int rowId) throws ConditionsObjectException { if (!isNew()) { throw new ConditionsObjectException("The row ID cannot be reassigned on an existing object."); } - this.rowId = rowId; + this.rowID = rowId; } + /** + * Convert this object to a string, which is a tab-separated row appropriate + * for display in a table for console output. + * + * @return The object converted to a string. + */ public String toString() { - StringBuffer sb = new StringBuffer(); + final StringBuffer sb = new StringBuffer(); sb.append(this.getRowId()); sb.append('\t'); for (Entry<String, Object> entries : this.getFieldValues().entrySet()) { @@ -65,4 +143,4 @@ } return sb.toString(); } -} +} Copied: java/trunk/conditions/src/main/java/org/hps/conditions/api/BaseConditionsObjectCollection.java (from r2653, java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObjectCollection.java) ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/AbstractConditionsObjectCollection.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/BaseConditionsObjectCollection.java Thu Apr 2 18:14:47 2015 @@ -14,76 +14,98 @@ /** * This class implements a collection API for ConditionsObjects, using a <code>LinkedHashSet</code>. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> * @param <ObjectType> The concrete type of the collection class. */ @SuppressWarnings("serial") -public abstract class AbstractConditionsObjectCollection<ObjectType extends ConditionsObject> extends LinkedHashSet<ObjectType> implements ConditionsObjectCollection<ObjectType> { - - protected TableMetaData tableMetaData = null; - protected int collectionId = -1; - protected ConditionsRecord conditionsRecord = null; - - /** - * This is the no argument constructor that would be used when creating a new collection - * that is not in the database. - */ - public AbstractConditionsObjectCollection() { - } - - /** - * This constructor uses the given conditions record and table meta data objects and will assign - * the collection ID from the conditions record. - * @param conditionsRecord - * @param tableMetaData - */ - public AbstractConditionsObjectCollection(ConditionsRecord conditionsRecord, TableMetaData tableMetaData) { +public class BaseConditionsObjectCollection<ObjectType extends ConditionsObject> extends LinkedHashSet<ObjectType> + implements ConditionsObjectCollection<ObjectType> { + + /** + * The associated table meta data. + */ + private TableMetaData tableMetaData = null; + + /** + * The collection ID which is -1 if the collection is not in the database. + */ + private int collectionID = -1; + + /** + * The associated conditions record information including run validity. + */ + private ConditionsRecord conditionsRecord = null; + + /** + * This is the no argument constructor that would be used when creating a new collection that is not in the + * database. + */ + public BaseConditionsObjectCollection() { + } + + /** + * This constructor uses the given conditions record and table meta data objects and will assign the collection ID + * from the conditions record. + * + * @param tableMetaData The table meta data. + * @param conditionsRecord The conditions record. + */ + public BaseConditionsObjectCollection(final ConditionsRecord conditionsRecord, final TableMetaData tableMetaData) { this.conditionsRecord = conditionsRecord; this.tableMetaData = tableMetaData; - this.collectionId = conditionsRecord.getCollectionId(); - } - + this.collectionID = conditionsRecord.getCollectionId(); + } + /** * This constructor is used to explicitly assign all class variable values. - * @param conditionsRecord - * @param tableMetaData - * @param collectionID - */ - public AbstractConditionsObjectCollection(ConditionsRecord conditionsRecord, TableMetaData tableMetaData, int collectionID) { + * + * @param conditionsRecord The conditions record. + * @param tableMetaData The table meta data. + * @param collectionID The new collection ID. + */ + public BaseConditionsObjectCollection(final ConditionsRecord conditionsRecord, final TableMetaData tableMetaData, + final int collectionID) { this.conditionsRecord = conditionsRecord; this.tableMetaData = tableMetaData; - this.collectionId = collectionID; - } - - /** - * Set the associated table meta data for this collection. - * Once set it cannot be reassigned, which will cause an exception to be thrown. - * @param tableMetaData - */ - public void setTableMetaData(TableMetaData tableMetaData) { + this.collectionID = collectionID; + } + + /** + * Set the associated table meta data for this collection. Once set it cannot be reassigned, which will cause an + * exception to be thrown. + * + * @param tableMetaData The table meta data for this collection. + */ + public final void setTableMetaData(final TableMetaData tableMetaData) { if (this.tableMetaData != null) { throw new RuntimeException("The table meta data cannot be reset once assigned."); } this.tableMetaData = tableMetaData; } - - /** - * Set the associated conditions record this collection. - * Once set it cannot be reassigned, which will cause an exception to be thrown. - * @param conditionsRecord - */ - public void setConditionsRecord(ConditionsRecord conditionsRecord) { + + /** + * Set the associated conditions record this collection. Once set it cannot be reassigned, which will cause an + * exception to be thrown. + * + * @param conditionsRecord The conditions record for the collection. + */ + public final void setConditionsRecord(final ConditionsRecord conditionsRecord) { if (this.conditionsRecord != null) { throw new RuntimeException("The conditions record cannot be reset once assigned."); } this.conditionsRecord = conditionsRecord; } - + /** * Add an object to the collection. - */ - public boolean add(ObjectType object) { + * <p> + * Implements {@link ConditionsObjectCollection#add(Object)}. + * + * @param object The object do add to the collection. + * @return True if the add operation succeeded. + */ + public boolean add(final ObjectType object) { if (contains(object)) { throw new IllegalArgumentException("Cannot add duplicate object " + object + " to collection."); } @@ -92,92 +114,136 @@ /** * Get the table meta data. - * @return - */ - public TableMetaData getTableMetaData() { + * <p> + * Implements {@link ConditionsObjectCollection#getTableMetaData()}. + * + * @return The table meta data for the collection. + */ + @Override + public final TableMetaData getTableMetaData() { return tableMetaData; } /** * Get the collection ID. - * @return - */ - public int getCollectionId() { + * <p> + * Implements {@link ConditionsObjectCollection#getCollectionId()}. + * + * @return The collection ID. + */ + @Override + public final int getCollectionId() { if (conditionsRecord != null) { - return conditionsRecord.getCollectionId(); + return conditionsRecord.getCollectionId(); } else { - return collectionId; - } - } - + return collectionID; + } + } + /** * Get the conditions record. - * @return - */ - public ConditionsRecord getConditionsRecord() { + * <p> + * Implements {@link ConditionsObjectCollection#getConditionsRecord()}. + * + * @return The conditions record for the collection. + */ + @Override + public final ConditionsRecord getConditionsRecord() { return conditionsRecord; } - - /** - * Set the collection ID. - * Once set it cannot be assign again, which will cause an exception. - * @param collectionId - * @throws ConditionsObjectException - */ - public void setCollectionId(int collectionId) throws ConditionsObjectException { - if (this.collectionId != -1) { - throw new ConditionsObjectException("The collectionId already has the value " + collectionId + " and cannot be reset."); - } - this.collectionId = collectionId; - } - - public void insert() throws ConditionsObjectException, SQLException { - // TODO: First check here if conditions record and/or collection ID is assigned already, - // in which case an error should be thrown as this is not a new collection. + + /** + * Set the collection ID. Once set it cannot be assigned again. + * <p> + * Implements {@link ConditionsObjectCollection#setCollectionID(int)}. + * + * @param collectionId The new collection ID. + * @throws ConditionsObjectException If the ID was already assigned. + */ + @Override + public final void setCollectionID(final int collectionId) throws ConditionsObjectException { + if (this.collectionID != -1) { + throw new ConditionsObjectException("The collectionId already has the value " + collectionId + + " and cannot be reset."); + } + this.collectionID = collectionId; + } + + /** + * Insert the collection into the database. + * <p> + * Implements {@link ConditionsObjectCollection#insert()}. + * + * @throws ConditionsObjectException If there was a problem inserting the object. + * @throws SQLException If there was a SQL syntax error while executing the operation. + */ + @Override + public final void insert() throws ConditionsObjectException, SQLException { DatabaseConditionsManager.getInstance().insertCollection(this); } - - // Should select records into this collection by collection ID. - public int select() { + + /** + * Select objects into this collection from the database. + * <p> + * Implements {@link ConditionsObjectCollection#select()}. + * + * @return The number of records selected. + */ + @Override + public final int select() { throw new UnsupportedOperationException("The select operation is not implemented yet."); } - - // Should delete all records by collection ID in the database and then clear the local objects. + + /** + * Delete the collection's object's from the database. + * <p> + * Implements {@link ConditionsObjectCollection#delete()}. + * + * @return The number of objects deleted. + */ + @Override public int delete() { throw new UnsupportedOperationException("The delete operation is not implemented yet."); } - - // Should update objects in the database with their values from this collection. - // All objects would need to have valid row IDs for this to work. - public int update() { + + /** + * Update the collection's objects in the database. + * <p> + * Implements {@link ConditionsObjectCollection#update()}. + * + * @return The number of records updated. + */ + @Override + public final int update() { throw new UnsupportedOperationException("The update operation is not implemented yet."); } - - /** - * Convert object to string. + + /** + * Convert this object to a string. + * @return The object converted to a string. */ public String toString() { - // TODO: Should print out column headers here if available from meta data. - StringBuffer buffer = new StringBuffer(); + final StringBuffer buffer = new StringBuffer(); for (ConditionsObject object : this) { buffer.append(object.toString()); buffer.append('\n'); } return buffer.toString(); - } - + } + /** * Get an object by index. + * * @param index The index in the set. * @return The object at the index. * @throws IndexOutOfBoundsException If the index value is invalid. */ - public ObjectType get(int index) { + public final ObjectType get(final int index) { if (index + 1 > this.size() || index < 0) { throw new IndexOutOfBoundsException("The index is out of bounds: " + index); } int current = 0; - Iterator<ObjectType> iterator = this.iterator(); + final Iterator<ObjectType> iterator = this.iterator(); ObjectType object = iterator.next(); while (current != index && iterator.hasNext()) { object = iterator.next(); @@ -185,50 +251,61 @@ } return object; } - + /** * Sort the collection in place. + * * @param comparator The comparator to use for sorting. */ - public void sort(Comparator<ObjectType> comparator) { - List<ObjectType> objects = new ArrayList<ObjectType>(this); + public void sort(final Comparator<ObjectType> comparator) { + final List<ObjectType> objects = new ArrayList<ObjectType>(this); Collections.sort(objects, comparator); clear(); addAll(objects); } - + /** * Get a sorted list of the objects, leaving original collection in place. + * * @param comparator The comparator to use for the sort. * @return A sorted list of the objects. */ @SuppressWarnings("unchecked") - public AbstractConditionsObjectCollection<ObjectType> sorted(Comparator<ObjectType> comparator) { - List<ObjectType> objects = new ArrayList<ObjectType>(this); + public BaseConditionsObjectCollection<ObjectType> sorted(final Comparator<ObjectType> comparator) { + final List<ObjectType> objects = new ArrayList<ObjectType>(this); Collections.sort(objects, comparator); - AbstractConditionsObjectCollection<ObjectType> collection = null; + BaseConditionsObjectCollection<ObjectType> collection = null; try { - collection = (AbstractConditionsObjectCollection<ObjectType>) getClass().newInstance(); + collection = (BaseConditionsObjectCollection<ObjectType>) getClass().newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } collection.addAll(objects); return collection; } - + + /** + * Sort this collection in place. + */ + @Override public void sort() { - AbstractConditionsObjectCollection<ObjectType> sortedCollection = sorted(); + final BaseConditionsObjectCollection<ObjectType> sortedCollection = sorted(); this.clear(); this.addAll(sortedCollection); } - - public AbstractConditionsObjectCollection<ObjectType> sorted() { - List<ObjectType> objects = new ArrayList<ObjectType>(this); + + /** + * Create and return a sorted collection, leaving the original collection unsorted. + * @return The sorted collection. + */ + @SuppressWarnings("unchecked") + @Override + public BaseConditionsObjectCollection<ObjectType> sorted() { + final List<ObjectType> objects = new ArrayList<ObjectType>(this); Collections.sort(objects, new DefaultConditionsObjectComparator()); - AbstractConditionsObjectCollection<ObjectType> collection = null; + BaseConditionsObjectCollection<ObjectType> collection = null; try { - // FIXME: This is kind of ugly. - collection = (AbstractConditionsObjectCollection<ObjectType>) getClass().newInstance(); + collection = ((BaseConditionsObjectCollection<ObjectType>) getClass().newInstance()); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObject.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObject.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObject.java Thu Apr 2 18:14:47 2015 @@ -3,71 +3,89 @@ import java.util.Comparator; /** - * This is an ORM interface for accessing conditions database information by - * row. It can handle new or existing records. The row ID values for new records are - * -1 which indicates they are not in the database yet. - * @author Jeremy McCormick <[log in to unmask]> + * This is an ORM interface for accessing conditions information by row from a database table. + * + * @author <a href="mailto:[log in to unmask]>Jeremy McCormick</a> */ public interface ConditionsObject { /** - * Get the row ID of this object. + * Get the row ID of this object, which will be -1 for records not in the database. + * * @return The database row ID. */ int getRowId(); /** - * Generic set method for field values. This will set the object to the - * 'dirty' state. - * @param fieldName The name of the field. - * @param fieldValue The field value. + * Set the value of a field. + * + * @param field The name of the field. + * @param value The field value. */ void setFieldValue(String field, Object value); /** * Set all of the field values on this object. - * @param fieldValues The FieldValueMap containing pairs of names and - * values. + * + * @param fieldValues The map containing pairs of field names and values. */ void setFieldValues(FieldValueMap fieldValues); - + /** * Get the map of field values. + * * @return The <code>FieldValueMap</code>. */ FieldValueMap getFieldValues(); /** * Get a field value, cast to the given class. + * * @param field The field value. + * @param type The class of the field. + * @param <T> The inferred type of the field. * @return The field value casted to type T. */ - public <T> T getFieldValue(Class<T> type, String field); + <T> T getFieldValue(Class<T> type, String field); /** * Get a field value with implicit return type. + * * @param field The field's name. + * @param <T> The inferred type of the field. * @return The field value cast to type. */ - public <T> T getFieldValue(String field); + <T> T getFieldValue(String field); /** - * Set the row ID of this object. This cannot be reset once set to a valid - * ID (e.g. not -1). + * Set the row ID of this object. This cannot be reset once set to a valid ID (e.g. not -1). + * * @param rowId The object's row ID. * @throws ConditionsObjectException if already set */ - public void setRowId(int rowId) throws ConditionsObjectException; - + void setRowID(int rowId) throws ConditionsObjectException; + /** - * Return true if this object is new, e.g. it does not have a valid row ID. - * This means that it does not have a database record in its table. + * Return true if this object is new, e.g. it does not have a valid row ID. This means that it does not have a + * database record in its table. + * * @return True if record is new. */ - public boolean isNew(); - + boolean isNew(); + + /** + * Default comparator for this interface which uses row ID. + */ static class DefaultConditionsObjectComparator implements Comparator<ConditionsObject> { - public int compare(ConditionsObject o1, ConditionsObject o2) { + + /** + * Compare objects according to standard Java conventions. + * + * @param o1 The first object. + * @param o2 The second object. + * @return The result of comparison operation. + */ + public int compare(final ConditionsObject o1, final ConditionsObject o2) { if (o1.getRowId() < o2.getRowId()) { return -1; } else if (o1.getRowId() > o2.getRowId()) { @@ -75,6 +93,6 @@ } else { return 0; } - } + } } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectCollection.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectCollection.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectCollection.java Thu Apr 2 18:14:47 2015 @@ -1,6 +1,3 @@ -/** - * - */ package org.hps.conditions.api; import java.sql.SQLException; @@ -10,66 +7,105 @@ import org.hps.conditions.database.TableMetaData; /** - * @author Jeremy McCormick <[log in to unmask]> + * An interface representing a collection of conditions objects. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> + * @param <ObjectType> The type of the conditions object contained in the collection. */ +// TODO: Rename to ConditionsObjectSet. public interface ConditionsObjectCollection<ObjectType extends ConditionsObject> extends Set<ObjectType> { /** * Get the table meta data. - * @return + * + * @return The table meta data. */ - public TableMetaData getTableMetaData(); + TableMetaData getTableMetaData(); /** * Get the collection ID. - * @return + * + * @return The collection ID. */ - public int getCollectionId(); - + int getCollectionId(); + /** * Get the conditions record. - * @return + * + * @return The conditions record. */ - public ConditionsRecord getConditionsRecord(); - + ConditionsRecord getConditionsRecord(); + /** - * Set the collection ID. - * Once set it cannot be assign again, which will cause an exception. - * @param collectionId - * @throws ConditionsObjectException + * Set the collection ID. Once set it cannot be assigned again, which will cause an exception. + * + * @param collectionId The collection ID. + * @throws ConditionsObjectException If reassignment is attempted. */ - public void setCollectionId(int collectionId) throws ConditionsObjectException; - - public void insert() throws ConditionsObjectException, SQLException; - - public int select(); - - public int delete(); - - public int update(); - + void setCollectionID(int collectionId) throws ConditionsObjectException; + /** - * Get an object by index. + * Insert all objects from the collection into the database. + * + * @throws ConditionsObjectException If there is a conditions object error. + * @throws SQLException If there is a SQL syntax or execution error. + */ + void insert() throws ConditionsObjectException, SQLException; + + /** + * Select objects into this collection by collection ID. + * + * @return The number of rows selected. + */ + int select(); + + /** + * Delete objects in this from the database. + * + * @return The number of rows deleted. + */ + int delete(); + + /** + * Update rows in the database from these objects. + * + * @return The number of rows updated. + */ + int update(); + + /** + * Get an object by its index. + * * @param index The index in the set. * @return The object at the index. * @throws IndexOutOfBoundsException If the index value is invalid. */ - public ObjectType get(int index); - + ObjectType get(int index); + /** * Sort the collection in place. + * * @param comparator The comparator to use for sorting. */ - public void sort(Comparator<ObjectType> comparator); - + void sort(Comparator<ObjectType> comparator); + /** * Get a sorted list of the objects, leaving original collection in place. + * * @param comparator The comparator to use for the sort. * @return A sorted list of the objects. */ - public AbstractConditionsObjectCollection<ObjectType> sorted(Comparator<ObjectType> comparator); - - public void sort(); - - public AbstractConditionsObjectCollection<ObjectType> sorted(); + BaseConditionsObjectCollection<ObjectType> sorted(Comparator<ObjectType> comparator); + + /** + * Sort the collection in place. + */ + void sort(); + + /** + * Get a new sorted collection. + * + * @return The new sorted collection. + */ + BaseConditionsObjectCollection<ObjectType> sorted(); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectException.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectException.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectException.java Thu Apr 2 18:14:47 2015 @@ -2,28 +2,52 @@ /** - * Generic Exception type throw by methods of {@link ConditionsObject} or other - * associated classes such as converters and collections. + * Thrown by methods of {@link ConditionsObject} or other associated classes + * such as converters and collections. */ @SuppressWarnings("serial") public final class ConditionsObjectException extends Exception { - ConditionsObject object; + /** + * The associated conditions object to the error. + */ + private ConditionsObject object; - public ConditionsObjectException(String message) { + /** + * Error with a message. + * + * @param message The error message. + */ + public ConditionsObjectException(final String message) { super(message); } - - public ConditionsObjectException(String message, Throwable cause) { + + /** + * Error with an associated throwable. + * + * @param message The error message. + * @param cause The error's cause. + */ + public ConditionsObjectException(final String message, final Throwable cause) { super(message, cause); } - public ConditionsObjectException(String message, ConditionsObject object) { + /** + * Error with a message and object. + * + * @param message The error message. + * @param object The associated conditions object. + */ + public ConditionsObjectException(final String message, final ConditionsObject object) { super(message); this.object = object; } + /** + * Get the associated conditions object to the error. + * @return The object associated with the error. + */ public ConditionsObject getConditionsObject() { return object; } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectUtilities.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectUtilities.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsObjectUtilities.java Thu Apr 2 18:14:47 2015 @@ -13,44 +13,51 @@ /** * This is a collection of utility methods for {@link ConditionsObject}. - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public final class ConditionsObjectUtilities { - - private ConditionsObjectUtilities() { + + /** + * Do not allow class to be instantiated. + */ + private ConditionsObjectUtilities() { } - + /** * Get the list of table names for the class. + * * @param type The class. * @return The list of table names. */ - public static String[] getTableNames(Class<? extends ConditionsObject> type) { - Table tableAnnotation = type.getAnnotation(Table.class); + public static String[] getTableNames(final Class<? extends ConditionsObject> type) { + final Table tableAnnotation = type.getAnnotation(Table.class); if (tableAnnotation != null) { - return tableAnnotation.names(); + return tableAnnotation.names(); } else { - return new String[]{}; + return new String[] {}; } } - + /** * Get the list of database field names for the class. + * * @param type The class. * @return The list of field names. */ - public static Set<String> getFieldNames(Class<? extends ConditionsObject> type) { - Set<String> fieldNames = new HashSet<String>(); + public static Set<String> getFieldNames(final Class<? extends ConditionsObject> type) { + final Set<String> fieldNames = new HashSet<String>(); for (Method method : type.getMethods()) { if (!method.getReturnType().equals(Void.TYPE)) { for (Annotation annotation : method.getAnnotations()) { if (annotation.annotationType().equals(Field.class)) { if (!Modifier.isPublic(method.getModifiers())) { - throw new RuntimeException("The method " + type.getName() + "." + method.getName() + " has a Field annotation but is not public."); + throw new RuntimeException("The method " + type.getName() + "." + method.getName() + + " has a Field annotation but is not public."); } - Field field = (Field) annotation; + final Field field = (Field) annotation; for (String fieldName : field.names()) { - if (fieldName != null && !fieldName.equals("")) { + if (fieldName != null && !("".equals(fieldName))) { fieldNames.add(fieldName); } } @@ -60,33 +67,38 @@ } return fieldNames; } - + /** * Get the class for the collection of the ConditionsObject type. + * * @param type The class of the ConditionsObject. * @return The class of the collection. */ @SuppressWarnings("unchecked") - public static Class<? extends AbstractConditionsObjectCollection<? extends ConditionsObject>> getCollectionType(Class<? extends ConditionsObject> type) { - String collectionClassName = type.getCanonicalName() + "$" + type.getSimpleName() + "Collection"; + public static Class<? extends BaseConditionsObjectCollection<? extends ConditionsObject>> getCollectionType( + final Class<? extends ConditionsObject> type) { + final String collectionClassName = type.getCanonicalName() + "$" + type.getSimpleName() + "Collection"; Class<?> rawCollectionClass; try { rawCollectionClass = Class.forName(collectionClassName); } catch (ClassNotFoundException e) { throw new RuntimeException("The type does not define a nested collection class.", e); } - if (!AbstractConditionsObjectCollection.class.isAssignableFrom(rawCollectionClass)) - throw new RuntimeException("The class " + rawCollectionClass.getSimpleName() + " does not extend ConditionsObjectCollection."); - return (Class<? extends AbstractConditionsObjectCollection<? extends ConditionsObject>>) rawCollectionClass; + if (!BaseConditionsObjectCollection.class.isAssignableFrom(rawCollectionClass)) { + throw new RuntimeException("The class " + rawCollectionClass.getSimpleName() + + " does not extend ConditionsObjectCollection."); + } + return (Class<? extends BaseConditionsObjectCollection<? extends ConditionsObject>>) rawCollectionClass; } - + /** * Find all available classes that extend ConditionsObject. + * * @return The set of all available classes that extend ConditionsObject. */ public static Set<Class<? extends ConditionsObject>> findConditionsObjectTypes() { - Reflections reflections = new Reflections("org.hps.conditions"); - Set<Class<? extends ConditionsObject>> objectTypes = new HashSet<Class<? extends ConditionsObject>>(); + final Reflections reflections = new Reflections("org.hps.conditions"); + final Set<Class<? extends ConditionsObject>> objectTypes = new HashSet<Class<? extends ConditionsObject>>(); for (Class<? extends ConditionsObject> objectType : reflections.getSubTypesOf(ConditionsObject.class)) { if (Modifier.isAbstract(objectType.getModifiers())) { continue; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsRecord.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsRecord.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsRecord.java Thu Apr 2 18:14:47 2015 @@ -17,134 +17,222 @@ import org.hps.conditions.database.TableMetaData; /** - * This class represents a single record from the primary conditions data table, - * which defines the validity range for a specific collection of conditions - * objects. - * - * @author Jeremy McCormick <[log in to unmask]> + * This class represents a single record from the primary conditions data table, which defines the validity range for a + * specific collection of conditions objects. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -@Table(names = {"conditions"}) +@Table(names = { "conditions" }) @Converter(converter = ConditionsRecordConverter.class) -public final class ConditionsRecord extends AbstractConditionsObject { - +public final class ConditionsRecord extends BaseConditionsObject { + /** * The concrete collection implementation, including sorting utilities. */ - public static class ConditionsRecordCollection extends AbstractConditionsObjectCollection<ConditionsRecord> { - + @SuppressWarnings("serial") + public static class ConditionsRecordCollection extends BaseConditionsObjectCollection<ConditionsRecord> { + /** * Sort using a comparator and leave the original collection unchanged. - * @param comparator - * @return - */ - public ConditionsRecordCollection sorted(Comparator<ConditionsRecord> comparator) { - List<ConditionsRecord> list = new ArrayList<ConditionsRecord>(this); + * + * @param comparator The comparison to use for sorting. + * @return The sorted collection. + */ + public final ConditionsRecordCollection sorted(final Comparator<ConditionsRecord> comparator) { + final List<ConditionsRecord> list = new ArrayList<ConditionsRecord>(this); Collections.sort(list, comparator); - ConditionsRecordCollection collection = new ConditionsRecordCollection(); + final ConditionsRecordCollection collection = new ConditionsRecordCollection(); collection.addAll(list); return collection; } - - public ConditionsRecordCollection sortedByUpdated() { + + /** + * Sort and return collection by updated date. + * + * @return The sorted collection. + */ + public final ConditionsRecordCollection sortedByUpdated() { return sorted(new UpdatedComparator()); } - - public ConditionsRecordCollection sortedByCreated() { + + /** + * Sort and return collection by creation date. + * + * @return The sorted collection. + */ + public final ConditionsRecordCollection sortedByCreated() { return sorted(new CreatedComparator()); } - - public ConditionsRecordCollection sortedByRunStart() { + + /** + * Sort and return by run start number. + * + * @return The sorted collection. + */ + public final ConditionsRecordCollection sortedByRunStart() { return sorted(new RunStartComparator()); } - - public ConditionsRecordCollection sortedByKey() { + + /** + * Sort and return by key (table name). + * + * @return The sorted collection. + */ + public final ConditionsRecordCollection sortedByKey() { return sorted(new KeyComparator()); } - + /** * Sort the collection in place. - * @param comparator - */ - public void sort(Comparator<ConditionsRecord> comparator) { - List<ConditionsRecord> list = new ArrayList<ConditionsRecord>(this); + * + * @param comparator The comparison to use for sorting. + */ + public final void sort(final Comparator<ConditionsRecord> comparator) { + final List<ConditionsRecord> list = new ArrayList<ConditionsRecord>(this); Collections.sort(list, comparator); this.clear(); this.addAll(list); } - - public void sortByUpdated() { + + /** + * Sort in place by updated date. + */ + public final void sortByUpdated() { this.sort(new UpdatedComparator()); } - - public void sortByCreated() { + + /** + * Sort in place by creation date. + */ + public final void sortByCreated() { sort(new CreatedComparator()); } - - public void sortByRunStart() { + + /** + * Sort in place by run start. + */ + public final void sortByRunStart() { sort(new RunStartComparator()); } - - public void sortByKey() { + + /** + * Sort in place by key. + */ + public final void sortByKey() { sort(new KeyComparator()); - } - - public Set<String> getConditionsKeys() { - Set<String> conditionsKeys = new HashSet<String>(); + } + + /** + * Get the unique conditions keys from the records in this collection. + * + * @return The set of unique conditions keys. + */ + public final Set<String> getConditionsKeys() { + final Set<String> conditionsKeys = new HashSet<String>(); for (ConditionsRecord record : this) { conditionsKeys.add(record.getName()); } return conditionsKeys; } - + + /** + * Compare conditions records by run start. + */ private static class RunStartComparator implements Comparator<ConditionsRecord> { + /** + * Compare the run start numbers of two conditions records. + * @param c1 The first conditions record. + * @param c2 The second conditions record. + * @return -1, 0, or 1 if first run number is less than, equal to, or greater than the second. + */ @Override - public int compare(ConditionsRecord c1, ConditionsRecord c2) { + public int compare(final ConditionsRecord c1, final ConditionsRecord c2) { if (c1.getRunStart() < c2.getRunStart()) { return -1; } else if (c1.getRunStart() > c2.getRunStart()) { return 1; - } + } return 0; } } - + + /** + * Compare conditions records by updated date. + */ private static class UpdatedComparator implements Comparator<ConditionsRecord> { + /** + * Compare the updated dates of two conditions records. + * @param c1 The first conditions record. + * @param c2 The second conditions record. + * @return -1, 0, or 1 if first date is less than, equal to, or greater than the second date. + */ @Override - public int compare(ConditionsRecord c1, ConditionsRecord c2) { - Date date1 = c1.getUpdated(); - Date date2 = c2.getUpdated(); + public int compare(final ConditionsRecord c1, final ConditionsRecord c2) { + final Date date1 = c1.getUpdated(); + final Date date2 = c2.getUpdated(); if (date1.before(date2)) { return -1; } else if (date1.after(date2)) { return 1; } - return 0; - } - } - + return 0; + } + } + + /** + * Compare conditions records by creation date. + */ private static class CreatedComparator implements Comparator<ConditionsRecord> { + /** + * Compare the creation dates of two conditions records. + * @param c1 The first conditions record. + * @param c2 The second conditions record. + * @return -1, 0, or 1 if first date is less than, equal to, or greater than the second date. + */ @Override - public int compare(ConditionsRecord c1, ConditionsRecord c2) { - Date date1 = c1.getCreated(); - Date date2 = c2.getCreated(); + public int compare(final ConditionsRecord c1, final ConditionsRecord c2) { + final Date date1 = c1.getCreated(); + final Date date2 = c2.getCreated(); if (date1.before(date2)) { return -1; } else if (date1.after(date2)) { return 1; } - return 0; - } - } - + return 0; + } + } + + /** + * Compare conditions records by their key (table name). + */ private static class KeyComparator implements Comparator<ConditionsRecord> { + /** + * Compare the keys (names) of two conditions records. + * @param c1 The first conditions record. + * @param c2 The second conditions record. + * @return -1, 0, or 1 if first name is less than, equal to, or greater than the second + * (using alphabetic comparison). + */ @Override - public int compare(ConditionsRecord c1, ConditionsRecord c2) { + public int compare(final ConditionsRecord c1, final ConditionsRecord c2) { return c1.getName().compareTo(c2.getName()); } } } - - public ConditionsRecord(int collectionId, int runStart, int runEnd, String name, String tableName, String notes, String tag) { + + /** + * Create a conditions record with fully qualified constructor. + * + * @param collectionId The ID of the associated conditions collection. + * @param runStart The starting run number. + * @param runEnd The ending run number. + * @param name The name of the conditions set (usually same as table name). + * @param tableName The name of the conditions data table. + * @param notes Text notes about this record. + * @param tag The conditions tag for grouping this record with others. + */ + public ConditionsRecord(final int collectionId, final int runStart, final int runEnd, final String name, + final String tableName, final String notes, final String tag) { this.setFieldValue("collection_id", collectionId); this.setFieldValue("run_start", runStart); this.setFieldValue("run_end", runEnd); @@ -156,135 +244,153 @@ this.setFieldValue("created_by", System.getProperty("user.name")); } + /** + * Create a "blank" conditions record. + */ public ConditionsRecord() { } - - // TODO: This should eventually be replaced by the generic insert method from the manager (if possible). + + /** + * Insert the conditions record into the database. + * @throws ConditionsObjectException If there are errors inserting the record. + */ public void insert() throws ConditionsObjectException { - if (fieldValues.size() == 0) + if (getFieldValues().size() == 0) { throw new ConditionsObjectException("There are no field values to insert."); - TableMetaData tableMetaData = DatabaseConditionsManager.getInstance().findTableMetaData(ConditionsRecordCollection.class).get(0); + } + final TableMetaData tableMetaData = DatabaseConditionsManager.getInstance() + .findTableMetaData(ConditionsRecordCollection.class).get(0); if (tableMetaData == null) { throw new ConditionsObjectException("Failed to get meta data for ConditionsRecord."); } - String query = QueryBuilder.buildInsert(tableMetaData.getTableName(), this.getFieldValues()); - //System.out.println(query); - List<Integer> keys = DatabaseConditionsManager.getInstance().updateQuery(query); + final String query = QueryBuilder.buildInsert(tableMetaData.getTableName(), this.getFieldValues()); + // System.out.println(query); + final List<Integer> keys = DatabaseConditionsManager.getInstance().updateQuery(query); if (keys.size() != 1) { throw new ConditionsObjectException("SQL insert returned wrong number of keys: " + keys.size()); } - rowId = keys.get(0); + setRowID(keys.get(0)); } /** * Get the starting run number. + * * @return The starting run number. */ - @Field(names = {"run_start"}) + @Field(names = { "run_start" }) public int getRunStart() { return getFieldValue("run_start"); } /** * Get the ending run number. + * * @return The ending run number. */ - @Field(names = {"run_end"}) + @Field(names = { "run_end" }) public int getRunEnd() { return getFieldValue("run_end"); } /** * Get the date this record was last updated. + * * @return The date this record was updated. */ - @Field(names = {"updated"}) + @Field(names = { "updated" }) public Date getUpdated() { return getFieldValue("updated"); } /** * Get the date this record was created. + * * @return The date this record was created. */ - @Field(names = {"created"}) + @Field(names = { "created" }) public Date getCreated() { return getFieldValue("created"); } /** * Get the name of the user who created this record. + * * @return The name of the person who created the record. */ - @Field(names = {"created_by"}) + @Field(names = { "created_by" }) public String getCreatedBy() { return getFieldValue("created_by"); } /** * Get the notes. + * * @return The notes about this condition. */ - @Field(names = {"notes"}) + @Field(names = { "notes" }) public String getNotes() { return getFieldValue("notes"); } /** - * Get the name of these conditions, which should be unique by run number. - * This is called the "key" in the table meta data to distinguish it from - * "table name". + * Get the name of these conditions, which should be unique by run number. This is called the "key" in the table + * meta data to distinguish it from "table name". + * * @return The name of the conditions. */ - @Field(names = {"name"}) + @Field(names = { "name" }) public String getName() { return getFieldValue("name"); } /** * Get the name of the table containing the actual raw conditions data. + * * @return The name of the table with the conditions data. */ - @Field(names = {"table_name"}) + @Field(names = { "table_name" }) public String getTableName() { return getFieldValue("table_name"); } /** * Get the collection ID, overriding this method from the parent class. + * * @return The collection ID. */ - @Field(names = {"collection_id"}) + @Field(names = { "collection_id" }) public int getCollectionId() { return getFieldValue("collection_id"); } /** * Get the string tag associated with these conditions. + * * @return The string tag. */ - @Field(names = {"tag"}) + @Field(names = { "tag" }) public String getTag() { return getFieldValue("tag"); } /** * Convert this record to a human readable string, one field per line. + * * @return This object represented as a string. */ public String toString() { - StringBuffer buff = new StringBuffer(); - buff.append("id: " + getRowId() + '\n'); - buff.append("name: " + getName() + '\n'); - buff.append("runStart: " + getRunStart() + '\n'); - buff.append("runEnd: " + getRunEnd() + '\n'); - buff.append("tableName: " + getTableName() + '\n'); - buff.append("collectionId: " + getCollectionId() + '\n'); - buff.append("updated: " + getUpdated() + '\n'); - buff.append("created: " + getCreated() + '\n'); - buff.append("tag: " + getTag() + '\n'); - buff.append("createdBy: " + getCreatedBy() + '\n'); - buff.append("notes: " + getNotes() + '\n'); - return buff.toString(); - } -} + final StringBuffer sb = new StringBuffer(); + sb.append("id: " + getRowId() + '\n'); + sb.append("name: " + getName() + '\n'); + sb.append("runStart: " + getRunStart() + '\n'); + sb.append("runEnd: " + getRunEnd() + '\n'); + sb.append("tableName: " + getTableName() + '\n'); + sb.append("collectionId: " + getCollectionId() + '\n'); + sb.append("updated: " + getUpdated() + '\n'); + sb.append("created: " + getCreated() + '\n'); + sb.append("tag: " + getTag() + '\n'); + sb.append("createdBy: " + getCreatedBy() + '\n'); + sb.append("notes: " + getNotes() + '\n'); + return sb.toString(); + } +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsSeries.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsSeries.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/ConditionsSeries.java Thu Apr 2 18:14:47 2015 @@ -2,22 +2,15 @@ import java.util.ArrayList; - /** - * This class represents a series of collections containing - * <tt>ConditionsObjects</tt>. It is used to conditions collections when there - * are multiple ones with the same key that are valid for the current run. - * - * @author Jeremy McCormick <[log in to unmask]> + * This class represents a series of collections containing <tt>ConditionsObjects</tt>. It is used to conditions + * collections when there are multiple ones with the same key that are valid for the current run. + * + * @param <ObjectType> The type of the conditions object. + * @param <CollectionType> The type of the conditions collection. + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @SuppressWarnings({ "serial" }) -public class ConditionsSeries<ObjectType extends ConditionsObject, CollectionType extends ConditionsObjectCollection<ObjectType>> extends ArrayList<ConditionsObjectCollection<ObjectType>> { - - Class<CollectionType> collectionType; - Class<ObjectType> objectType; - - public ConditionsSeries(Class<ObjectType> objectType, Class<CollectionType> collectionType) { - this.collectionType = collectionType; - this.objectType = objectType; - } -} +public class ConditionsSeries<ObjectType extends ConditionsObject, CollectionType extends ConditionsObjectCollection<ObjectType>> + extends ArrayList<ConditionsObjectCollection<ObjectType>> { +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/api/FieldValueMap.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/FieldValueMap.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/FieldValueMap.java Thu Apr 2 18:14:47 2015 @@ -4,7 +4,8 @@ /** * Simple class extending <code>java.lang.Map</code> that maps field names - * to values. + * to values for conditions objects. */ +@SuppressWarnings("serial") public final class FieldValueMap extends LinkedHashMap<String, Object> { } Added: java/trunk/conditions/src/main/java/org/hps/conditions/api/package-info.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/api/package-info.java (added) +++ java/trunk/conditions/src/main/java/org/hps/conditions/api/package-info.java Thu Apr 2 18:14:47 2015 @@ -0,0 +1,13 @@ +/** + * This package contains interfaces and abstract classes, along with some + * implementations, of the database conditions API for HPS. These classes + * include simple ORM between conditions objects and the database. + * + * @author Jeremy McCormick <[log in to unmask]> + * + * @see ConditionsObject + * @see ConditionsObjectCollection + * @see ConditionsSeries + * @see ConditionsRecord + */ +package org.hps.conditions.api; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamConditions.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamConditions.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamConditions.java Thu Apr 2 18:14:47 2015 @@ -1,35 +1,38 @@ package org.hps.conditions.beam; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; import org.hps.conditions.database.Table; /** - * <p> * Beam-related detector conditions, including current, position * in X and Y, and energy. - * <p> - * Unless otherwise stated, these are assumed to be average values + * <p> + * Unless otherwise stated, these are assumed to be average values * for an entire run. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Table(names = {"beam"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.ERROR) -public final class BeamConditions extends AbstractConditionsObject { - +public final class BeamConditions extends BaseConditionsObject { + /** * Collection implementation for this class. */ - public final static class BeamConditionsCollection extends AbstractConditionsObjectCollection<BeamConditions> { + @SuppressWarnings("serial") + public static final class BeamConditionsCollection extends BaseConditionsObjectCollection<BeamConditions> { } - + + /** + * No arg constructor. + */ public BeamConditions() { } - + /** * Get the average beam current (nA). * A value of 0 indicates there was no beam. @@ -40,7 +43,7 @@ public Double getCurrent() { return getFieldValue("current"); } - + /** * Get the average beam position in X (mm). * @return The beam position (mm). @@ -49,7 +52,7 @@ public Double getPositionX() { return getFieldValue("position_x"); } - + /** * Get the average beam position in Y (mm). * @return The beam position (mm). @@ -58,7 +61,7 @@ public Double getPositionY() { return getFieldValue("position_y"); } - + /** * Get the beam energy (GeV). * A value of 0 indicates there was no beam. @@ -68,5 +71,5 @@ @Field(names = {"energy"}) public Double getEnergy() { return getFieldValue("energy"); - } + } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamCurrent.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamCurrent.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/beam/BeamCurrent.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.beam; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -9,13 +9,18 @@ /** * This class is a conditions object for integrated beam current values. - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Table(names = {"beam_current"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class BeamCurrent extends AbstractConditionsObject { +public final class BeamCurrent extends BaseConditionsObject { - public static class BeamCurrentCollection extends AbstractConditionsObjectCollection<BeamCurrent> { + /** + * Collection implementation for this class. + */ + @SuppressWarnings("serial") + public static class BeamCurrentCollection extends BaseConditionsObjectCollection<BeamCurrent> { } /** Modified: java/trunk/conditions/src/main/java/org/hps/conditions/beam/ImportBeamConditionsEngRun.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/beam/ImportBeamConditionsEngRun.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/beam/ImportBeamConditionsEngRun.java Thu Apr 2 18:14:47 2015 @@ -17,93 +17,114 @@ * <p> * Import beam measurements into the database from a text file. * <p> - * This has the format:<br/> + * This has the format:<br/> * run current x y * <p> * The beam energy is hard-coded to 1.92 GeV for now, pending updates with better information. - * + * * @author Jeremy McCormick <[log in to unmask]> */ public final class ImportBeamConditionsEngRun { - static double beamEnergy = 1.92; - static double nullValue = -999.0; - + /** + * Nominal beam energy for Eng Run. + */ + private static final double BEAM_ENERGY = 1.92; + + /** + * Null value from the input text file. + */ + private static final double NULL_VALUE = -999.0; + + /** + * Class should not be instantiated. + */ private ImportBeamConditionsEngRun() { } - - public static void main(String[] args) throws Exception { - + + /** + * Import the Eng Run beam conditions from a text file. + * @param args The argument list. + * @throws Exception If there is an error importing the text file. + */ + public static void main(final String[] args) throws Exception { + if (args.length == 0) { throw new RuntimeException("missing file list argument"); } - - String fileName = args[0]; + + final String fileName = args[0]; if (!new File(fileName).exists()) { throw new IOException("The file " + fileName + " does not exist."); } - - Map<Integer, BeamConditions> beamMap = new LinkedHashMap<Integer, BeamConditions>(); - - BufferedReader reader = new BufferedReader(new FileReader(fileName)); + + final Map<Integer, BeamConditions> beamMap = new LinkedHashMap<Integer, BeamConditions>(); + + final BufferedReader reader = new BufferedReader(new FileReader(fileName)); String line; while ((line = reader.readLine()) != null) { - - String[] values = line.split(" "); - - BeamConditions beam = new BeamConditions(); - + + final String[] values = line.split(" "); + + final BeamConditions beam = new BeamConditions(); + setValue(beam, "current", values[1]); setValue(beam, "position_x", values[2]); setValue(beam, "position_y", values[3]); - + if (beam.getFieldValue("current") == null) { // Use null value to indicate beam was not measured. beam.setFieldValue("energy", null); - } else if (((Double)beam.getFieldValue("current")) == 0) { + } else if (((Double) beam.getFieldValue("current")) == 0) { // Use zero for no beam. beam.setFieldValue("energy", 0); } else { // Use nominal beam energy from ECAL commissioning. - beam.setFieldValue("energy", beamEnergy); + beam.setFieldValue("energy", BEAM_ENERGY); } - + beamMap.put(Integer.parseInt(values[0]), beam); } reader.close(); - + System.out.println("printing beam conditions parsed from " + fileName + " ..."); System.out.println("run id current x y energy"); for (Entry<Integer, BeamConditions> entry : beamMap.entrySet()) { System.out.print(entry.getKey() + " "); System.out.println(entry.getValue() + " "); } - - DatabaseConditionsManager manager = DatabaseConditionsManager.getInstance(); + + final DatabaseConditionsManager manager = DatabaseConditionsManager.getInstance(); manager.setLogLevel(Level.ALL); - + for (Entry<Integer, BeamConditions> entry : beamMap.entrySet()) { - int run = entry.getKey(); - BeamConditions beam = entry.getValue(); - int collectionId = manager.getNextCollectionID("beam"); - ConditionsRecord record = + final int run = entry.getKey(); + final BeamConditions beam = entry.getValue(); + final int collectionId = manager.getNextCollectionID("beam"); + final ConditionsRecord record = new ConditionsRecord(collectionId, run, run, "beam", "beam", "imported from HPS_Runs.pdf", "eng_run"); System.out.println(record); System.out.println(beam); - BeamConditionsCollection collection = new BeamConditionsCollection(); + final BeamConditionsCollection collection = new BeamConditionsCollection(); collection.add(beam); manager.insertCollection(collection); record.insert(); - } + } manager.closeConnection(); - } - - static void setValue(BeamConditions beam, String fieldName, String rawValue) { - double value = Double.parseDouble(rawValue); - if (value != nullValue) { + } + + /** + * Set the value of the beam current. + * @param beam The beam conditions object. + * @param fieldName The name of the field. + * @param rawValue The raw value from the text file. + */ + static void setValue(final BeamConditions beam, final String fieldName, final String rawValue) { + final double value = Double.parseDouble(rawValue); + if (value != NULL_VALUE) { beam.setFieldValue(fieldName, value); } else { beam.setFieldValue(fieldName, null); } - } -} + } +} Added: java/trunk/conditions/src/main/java/org/hps/conditions/beam/package-info.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/beam/package-info.java (added) +++ java/trunk/conditions/src/main/java/org/hps/conditions/beam/package-info.java Thu Apr 2 18:14:47 2015 @@ -0,0 +1,6 @@ +/** + * Provides access to beam parameters through the conditions system. + * + * @author Jeremy McCormick <[log in to unmask]> + */ +package org.hps.conditions.beam; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/AbstractCommand.java Thu Apr 2 18:14:47 2015 @@ -8,36 +8,55 @@ import org.apache.commons.cli.PosixParser; /** - * This is the API that sub-commands must implement in the conditions command - * line interface. - * - * @author Jeremy McCormick <[log in to unmask]> + * This is the API that sub-commands such as 'load' or 'print' must implement + * in the conditions command line interface. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ abstract class AbstractCommand { - String name; - String description; - Options options = new Options(); - Parser parser = new PosixParser(); - CommandLine commandLine; - boolean verbose = false; + /** + * The name of the (sub)command. + */ + private String name; + + /** + * The description of the command. + */ + private String description; + + /** + * The options this command takes on the command line (Apache CLI). + */ + private final Options options; + + /** + * The parser for the options. + */ + private final Parser parser = new PosixParser(); + + /** + * Verbose setting. + */ + private boolean verbose = false; /** * Class constructor. * @param name The string that invokes this command. * @param description The description of this command. + * @param options The command's options (Apache CLI). */ - AbstractCommand(String name, String description) { + AbstractCommand(final String name, final String description, final Options options) { this.name = name; this.description = description; - options.addOption("h", false, "Print help for this command"); + this.options = options; } /** * Get the name of this command. * @return A String of the name of this command. */ - String getName() { + final String getName() { return this.name; } @@ -45,7 +64,7 @@ * Get the description of this command. * @return A String of the description of this command. */ - String getDescription() { + protected final String getDescription() { return this.description; } @@ -53,16 +72,15 @@ * Options for this command. * @return Options object for this command. */ - Options getOptions() { + protected final Options getOptions() { return options; } /** * Print the usage of this sub-command. - * @param doExit Whether or not to exit after printing usage. */ - void printUsage() { - HelpFormatter help = new HelpFormatter(); + protected final void printUsage() { + final HelpFormatter help = new HelpFormatter(); help.printHelp(getName(), getOptions()); } @@ -70,16 +88,25 @@ * Set whether verbose output is enabled. * @param verbose True to enable verbose output. */ - void setVerbose(boolean verbose) { + final void setVerbose(final boolean verbose) { this.verbose = verbose; } /** - * Execute the command with the arguments. This is the only method that - * sub-classes must implement. + * Get verbose flag. + * @return The verbose flag. + */ + protected boolean getVerbose() { + return verbose; + } + + /** + * Parse the sub-command's options. * @param arguments The sub-command's arguments. + * @return The parsed command line. */ - void execute(String[] arguments) { + protected final CommandLine parse(final String[] arguments) { + CommandLine commandLine = null; try { commandLine = parser.parse(options, arguments); } catch (ParseException e) { @@ -89,5 +116,12 @@ this.printUsage(); System.exit(0); } + return commandLine; } + + /** + * The sub-command execution method that should be implemented by sub-classes. + * @param arguments The command's argument list. + */ + abstract void execute(final String[] arguments); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/cli/AddCommand.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/cli/AddCommand.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/AddCommand.java Thu Apr 2 18:14:47 2015 @@ -3,39 +3,61 @@ import java.io.PrintStream; import java.util.Date; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; import org.hps.conditions.api.ConditionsObjectException; import org.hps.conditions.api.ConditionsRecord; import org.hps.conditions.api.FieldValueMap; import org.hps.conditions.database.DatabaseConditionsManager; /** - * This is a command for the conditions CLI that will add a conditions record, - * making a conditions set with a particular collection ID available by - * run number via the {@link org.hps.conditions.database.DatabaseConditionsManager}. - * - * @author Jeremy McCormick <[log in to unmask]> + * This is a command for the conditions CLI that will add a conditions record, making a conditions set with a particular + * collection ID available by run number via the {@link org.hps.conditions.database.DatabaseConditionsManager}. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public class AddCommand extends AbstractCommand { - - PrintStream ps = System.out; - + + /** + * For printing out messages. + */ + private final PrintStream ps = System.out; + + /** + * Define command line options. + */ + private static final Options OPTIONS = new Options(); + static { + OPTIONS.addOption(new Option("h", false, "Show help for add command")); + OPTIONS.addOption("r", true, "The starting run number (required)"); + OPTIONS.getOption("r").setRequired(true); + OPTIONS.addOption("e", true, "The ending run number (default is starting run number)"); + OPTIONS.addOption("t", true, "The table name (required)"); + OPTIONS.getOption("t").setRequired(true); + OPTIONS.addOption("c", true, "The collection ID (required)"); + OPTIONS.getOption("c").setRequired(true); + OPTIONS.addOption("T", true, "A tag value (optional)"); + OPTIONS.addOption("u", true, "Your user name (optional)"); + OPTIONS.addOption("m", true, "The notes about this conditions set (optional)"); + } + + /** + * Class constructor. + */ AddCommand() { - super("add", "Add a conditions record to associate a collection to a run range"); - options.addOption("r", true, "The starting run number (required)"); - options.getOption("r").setRequired(true); - options.addOption("e", true, "The ending run number (default is starting run number)"); - options.addOption("t", true, "The table name (required)"); - options.getOption("t").setRequired(true); - options.addOption("c", true, "The collection ID (required)"); - options.getOption("c").setRequired(true); - options.addOption("T", true, "A tag value (optional)"); - options.addOption("u", true, "Your user name (optional)"); - options.addOption("m", true, "The notes about this conditions set (optional)"); + super("add", "Add a conditions record to associate a collection to a run range", OPTIONS); } - - void execute(String[] arguments) { - super.execute(arguments); - + + /** + * Execute the command with the given arguments. + * + * @param arguments The command line arguments. + */ + final void execute(final String[] arguments) { + + final CommandLine commandLine = parse(arguments); + // This command has 3 required options. if (commandLine.getOptions().length == 0) { this.printUsage(); @@ -43,13 +65,13 @@ } // Run start (required). - int runStart; + final int runStart; if (commandLine.hasOption("r")) { runStart = Integer.parseInt(commandLine.getOptionValue("r")); } else { throw new RuntimeException("Missing required -r option with run number."); } - + // Run end. int runEnd = runStart; if (commandLine.hasOption("e")) { @@ -62,8 +84,8 @@ tableName = commandLine.getOptionValue("t"); } else { throw new RuntimeException("Missing required -t argument with table name"); - } - String name = tableName; + } + final String name = tableName; // Collection ID (required). int collectionId; @@ -72,38 +94,31 @@ } else { throw new RuntimeException("Missing required -c argument with collection ID"); } - + // User name. String createdBy = System.getProperty("user.name"); if (commandLine.hasOption("u")) { createdBy = commandLine.getOptionValue("u"); } - + // Tag to assign (optional). String tag = null; if (commandLine.hasOption("T")) { tag = commandLine.getOptionValue("T"); } - + // Notes (optional). String notes = null; if (commandLine.hasOption("m")) { notes = commandLine.getOptionValue("m"); } - + // Create the conditions record to insert. - ConditionsRecord conditionsRecord = createConditionsRecord( - runStart, - runEnd, - tableName, - name, - collectionId, - createdBy, - tag, - notes); + final ConditionsRecord conditionsRecord = createConditionsRecord(runStart, runEnd, tableName, name, + collectionId, createdBy, tag, notes); try { boolean createdConnection = false; - DatabaseConditionsManager manager = DatabaseConditionsManager.getInstance(); + final DatabaseConditionsManager manager = DatabaseConditionsManager.getInstance(); if (!DatabaseConditionsManager.getInstance().isConnected()) { createdConnection = manager.openConnection(); } @@ -117,19 +132,23 @@ } /** - * @param runStart - * @param runEnd - * @param tableName - * @param name - * @param collectionId - * @param createdBy - * @param tag - * @param notes - * @return + * Create a conditions record. + * + * @param runStart The run start. + * @param runEnd The run end. + * @param tableName The table name. + * @param name The key name. + * @param collectionId The collection ID. + * @param createdBy The user name. + * @param tag The conditions tag. + * @param notes The text notes. + * @return The new conditions record. */ - private ConditionsRecord createConditionsRecord(int runStart, int runEnd, String tableName, String name, int collectionId, String createdBy, String tag, String notes) { - ConditionsRecord conditionsRecord = new ConditionsRecord(); - FieldValueMap fieldValues = new FieldValueMap(); + // FIXME: Too many method parameters (max 7 is recommended). + private ConditionsRecord createConditionsRecord(final int runStart, final int runEnd, final String tableName, + final String name, final int collectionId, final String createdBy, final String tag, final String notes) { + final ConditionsRecord conditionsRecord = new ConditionsRecord(); + final FieldValueMap fieldValues = new FieldValueMap(); fieldValues.put("run_start", runStart); fieldValues.put("run_end", runEnd); fieldValues.put("table_name", tableName); @@ -146,4 +165,4 @@ fieldValues.put("created", new Date()); return conditionsRecord; } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/cli/CommandLineTool.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/cli/CommandLineTool.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/CommandLineTool.java Thu Apr 2 18:14:47 2015 @@ -18,41 +18,74 @@ import org.lcsim.util.log.LogUtil; /** + * This class is a command-line tool for performing commands on the conditions database using sub-commands for + * operations such as 'add' and 'print'. * <p> - * This class is a command-line tool for performing commands on the conditions - * database. It has sub-commands much like the cvs or svn clients. - * <p> - * Command line options allow a custom connection properties file or XML - * configuration to be supplied by the user which will override the default. - * - * @author Jeremy McCormick <[log in to unmask]> + * Command line options can be used to supply a custom connection properties file or XML which will override the + * default. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ +// FIXME: Print outs should use conditions manager's log settings and not boolean verbose flag. public class CommandLineTool { - - static Logger logger = LogUtil.create(CommandLineTool.class.getSimpleName(), new DefaultLogFormatter(), Level.WARNING); - - Options options = new Options(); - Map<String, AbstractCommand> commands = new HashMap<String, AbstractCommand>(); - PosixParser parser = new PosixParser(); - DatabaseConditionsManager conditionsManager; - boolean verbose = false; - - public static void main(String[] arguments) { + + /** + * Setup logging. + */ + private static final Logger LOGGER = + LogUtil.create(CommandLineTool.class.getSimpleName(), new DefaultLogFormatter(), Level.WARNING); + + /** + * The top level options (does not include sub-command options). + */ + private Options options = new Options(); + + /** + * The map of named command handlers. + */ + private Map<String, AbstractCommand> commands = new HashMap<String, AbstractCommand>(); + + /** + * The options parser. + */ + private PosixParser parser = new PosixParser(); + + /** + * The database conditions system manager. + */ + private DatabaseConditionsManager conditionsManager; + + /** + * The verbose setting. + */ + private boolean verbose = false; + + /** + * The main method for the class. + * + * @param arguments The command line arguments. + */ + public static void main(final String[] arguments) { CommandLineTool.create().run(arguments); } - void run(String[] arguments) { + /** + * Run the command line tool, parsing the command line and sending arguments to sub-command handlers. + * + * @param arguments The command line arguments passed directly from {@link #main(String[])}. + */ + private void run(final String[] arguments) { try { if (arguments.length == 0) { printUsage(); exit(0); } - + CommandLine commandLine = null; try { commandLine = parser.parse(options, arguments, true); } catch (ParseException e) { - logger.log(Level.SEVERE, "error parsing the options", e); + LOGGER.log(Level.SEVERE, "error parsing the options", e); printUsage(); exit(1); } @@ -64,24 +97,24 @@ // Set verbosity. if (commandLine.hasOption("v")) { - logger.setLevel(Level.ALL); - logger.getHandlers()[0].setLevel(Level.ALL); + LOGGER.setLevel(Level.ALL); + LOGGER.getHandlers()[0].setLevel(Level.ALL); verbose = true; - logger.config("verbose mode enabled"); + LOGGER.config("verbose mode enabled"); } // Setup conditions manager from command line options. setupConditionsManager(commandLine); // Get the sub-command to use. - String commandName = commandLine.getArgs()[0]; - AbstractCommand command = commands.get(commandName); + final String commandName = commandLine.getArgs()[0]; + final AbstractCommand command = commands.get(commandName); if (command == null) { throw new IllegalArgumentException("Unknown command " + commandName); } // Copy remaining arguments for sub-command. - String[] commandArguments = new String[commandLine.getArgs().length - 1]; + final String[] commandArguments = new String[commandLine.getArgs().length - 1]; System.arraycopy(commandLine.getArgs(), 1, commandArguments, 0, commandArguments.length); // Excecute the sub-command. @@ -95,89 +128,110 @@ } } - void setupConditionsManager(CommandLine commandLine) { - - logger.info("setting up conditions manager"); - + /** + * Setup the conditions system based on command line arguments. + * + * @param commandLine The parsed command line arguments. + */ + private void setupConditionsManager(final CommandLine commandLine) { + + LOGGER.info("setting up conditions manager"); + // Create new manager. conditionsManager = DatabaseConditionsManager.getInstance(); // Set log level. - conditionsManager.setLogLevel(logger.getLevel()); + conditionsManager.setLogLevel(LOGGER.getLevel()); // Connection properties. if (commandLine.hasOption("p")) { - File connectionPropertiesFile = new File(commandLine.getOptionValue("p")); + final File connectionPropertiesFile = new File(commandLine.getOptionValue("p")); conditionsManager.setConnectionProperties(connectionPropertiesFile); - logger.config("connection properties -p " + connectionPropertiesFile); - } - + LOGGER.config("connection properties -p " + connectionPropertiesFile); + } + // XML config. if (commandLine.hasOption("x")) { - File xmlConfigFile = new File(commandLine.getOptionValue("x")); + final File xmlConfigFile = new File(commandLine.getOptionValue("x")); conditionsManager.setXmlConfig(xmlConfigFile); - logger.config("XML config -x " + xmlConfigFile); - } - + LOGGER.config("XML config -x " + xmlConfigFile); + } + // If there is a run number or detector number then attempt to initialize the conditions system. if (commandLine.hasOption("r") || commandLine.hasOption("d")) { - - logger.config("detector name or run number supplied so manager will be initialized"); + + LOGGER.config("detector name or run number supplied so manager will be initialized"); // Set detector name. String detectorName = null; if (commandLine.hasOption("d")) { detectorName = commandLine.getOptionValue("d"); - logger.config("detector -d " + detectorName); + LOGGER.config("detector -d " + detectorName); } else { detectorName = "HPS-ECalCommissioning-v2"; - logger.config("default detector " + detectorName + " is being used"); + LOGGER.config("default detector " + detectorName + " is being used"); } // Get run number. Integer run = null; if (commandLine.hasOption("r")) { run = Integer.parseInt(commandLine.getOptionValue("r")); - logger.config("run -r " + run); + LOGGER.config("run -r " + run); } else { run = 0; - logger.config("default run number " + run + " is being used"); + LOGGER.config("default run number " + run + " is being used"); } // Setup the conditions manager with user detector name and run number. try { - logger.config("initializing conditions manager with detector " + detectorName + " and run " + run); + LOGGER.config("initializing conditions manager with detector " + detectorName + " and run " + run); DatabaseConditionsManager.getInstance().setDetector(detectorName, run); - logger.config("conditions manager initialized successfully"); - logger.getHandlers()[0].flush(); + LOGGER.config("conditions manager initialized successfully"); + LOGGER.getHandlers()[0].flush(); } catch (ConditionsNotFoundException e) { throw new RuntimeException(e); } } } - void printUsage() { - HelpFormatter help = new HelpFormatter(); - StringBuffer s = new StringBuffer(); + /** + * Print the usage statement for this tool to the console. + */ + final void printUsage() { + final HelpFormatter help = new HelpFormatter(); + final StringBuffer s = new StringBuffer(); for (String command : commands.keySet()) { s.append(command + '\n'); } help.printHelp("CommandLineTool", "Commands:\n" + s.toString(), options, ""); } - void exit(int status) { + /** + * Exit with the given status. + * + * @param status The exit status. + */ + private void exit(final int status) { System.exit(status); } - void registerCommand(AbstractCommand command) { + /** + * Register a sub-command handler. + * @param command The sub-command handler. + */ + private void registerCommand(final AbstractCommand command) { if (commands.containsKey(command.getName())) { throw new IllegalArgumentException("There is already a command called " + command.getName()); } commands.put(command.getName(), command); } - static CommandLineTool create() { - CommandLineTool cli = new CommandLineTool(); + /** + * Create a basic instance of this class. + * @return The instance of this class. + */ + private static CommandLineTool create() { + final CommandLineTool cli = new CommandLineTool(); cli.options.addOption(new Option("h", false, "Print help and exit")); cli.options.addOption(new Option("d", true, "Set the detector name")); cli.options.addOption(new Option("r", true, "Set the run number")); @@ -189,4 +243,4 @@ cli.registerCommand(new AddCommand()); return cli; } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/cli/LoadCommand.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/cli/LoadCommand.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/LoadCommand.java Thu Apr 2 18:14:47 2015 @@ -8,42 +8,57 @@ import java.util.List; import java.util.StringTokenizer; +import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; import org.hps.conditions.database.DatabaseConditionsManager; import org.hps.conditions.database.QueryBuilder; /** + * This is a sub-command to add conditions data using an input text file. The file should be ASCII text that is tab or + * space delimited and includes headers with the names of the database columns. (These must match exactly!) The user + * must supply a table name as the target for the SQL insert. An optional collection ID can be supplied, which may not + * exist already in the table. Otherwise, the command will fail. By default, the next collection ID will be found by the + * conditions manager. * <p> - * This is a sub-command to add conditions data using an input text file. The - * file should be ASCII text that is tab or space delimited and includes headers - * with the names of the database columns. (These must match exactly!) The user - * must supply a table name as the target for the SQL insert. An optional - * collection ID can be supplied, which may not exist already in the table. - * Otherwise, the command will fail. By default, the next collection ID will be - * found by the conditions manager. - * <p> - * * <pre> - * java -cp hps-distribution-bin.jar org.hps.conditions.cli.CommandLineTool -p conditions_dev_local.properties \ - * load -t scratch_svt_gains -f ./scratch_svt_gains.txt -c 1 + * java -cp hps-distribution-bin.jar org.hps.conditions.cli.CommandLineTool \ + * -p conditions_dev_local.properties load -t scratch_svt_gains -f ./scratch_svt_gains.txt -c 1 * </pre> - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ class LoadCommand extends AbstractCommand { - LoadCommand() { - super("load", "Load a set of conditions into the database from a text file"); - this.options.addOption(new Option("t", true, "Set the name of the target table in the database")); - this.options.addOption(new Option("c", true, "Set the collection ID of this conditions set")); - this.options.addOption(new Option("f", true, "Set the input data file")); + /** + * Define command options. + */ + private static final Options OPTIONS = new Options(); + static { + OPTIONS.addOption(new Option("h", false, "Show help for load command")); + OPTIONS.addOption(new Option("t", true, "Set the name of the target table in the database")); + OPTIONS.addOption(new Option("c", true, "Set the collection ID of this conditions set")); + OPTIONS.addOption(new Option("f", true, "Set the input data file")); } + /** + * Class constructor. + */ + LoadCommand() { + super("load", "Load a set of conditions into the database from a text file", OPTIONS); + } + + /** + * Execute the 'load' command with the given arguments. + * + * @param arguments The command arguments. + */ @Override - public void execute(String[] arguments) { - super.execute(arguments); - - String fileName = commandLine.getOptionValue("f"); + public void execute(final String[] arguments) { + + final CommandLine commandLine = parse(arguments); + + final String fileName = commandLine.getOptionValue("f"); if (fileName == null) { throw new IllegalArgumentException("Missing file argument."); } @@ -51,47 +66,58 @@ throw new IllegalArgumentException("Input file does not exist: " + fileName); } - String tableName = commandLine.getOptionValue("t"); + final String tableName = commandLine.getOptionValue("t"); if (tableName == null) { throw new IllegalArgumentException("Missing table name."); } - DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); + final DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); boolean openedConnection = false; if (!conditionsManager.isConnected()) { openedConnection = conditionsManager.openConnection(); } - + int collectionID; if (commandLine.getOptionValue("c") != null) { collectionID = Integer.parseInt(commandLine.getOptionValue("c")); if (conditionsManager.collectionExists(tableName, collectionID)) { - throw new IllegalArgumentException("The user supplied collection ID " + collectionID + " already exists in this table."); + throw new IllegalArgumentException("The user supplied collection ID " + collectionID + + " already exists in this table."); } } else { collectionID = conditionsManager.getNextCollectionID(tableName); } - List<String> columnNames = new ArrayList<String>(); - List<List<String>> rows = new ArrayList<List<String>>(); + final List<String> columnNames = new ArrayList<String>(); + final List<List<String>> rows = new ArrayList<List<String>>(); parseFile(fileName, columnNames, rows); - String insertSql = QueryBuilder.buildInsert(tableName, collectionID, columnNames, rows); - if (verbose) + final String insertSql = QueryBuilder.buildInsert(tableName, collectionID, columnNames, rows); + if (getVerbose()) { System.out.println(insertSql); - // FIXME: This call should go through an object API like ConditionsObjectCollection.insert rather than the manager directly. - List<Integer> IDs = conditionsManager.updateQuery(insertSql); - System.out.println("Inserted " + IDs.size() + " new rows into table " + tableName + " with collection_id " + collectionID); + } + // FIXME: This call should go through an object API like ConditionsObjectCollection.insert rather than the + // manager directly. + final List<Integer> ids = conditionsManager.updateQuery(insertSql); + System.out.println("Inserted " + ids.size() + " new rows into table " + tableName + " with collection_id " + + collectionID); conditionsManager.closeConnection(openedConnection); } - void parseFile(String fileName, List<String> columnNames, List<List<String>> rows) { - File inputFile = new File(fileName); + /** + * Parse an input text file and add column names and row data to the input lists. + * @param fileName The name of the text file. + * @param columnNames The list of columns (modified by this method). + * @param rows The list of rows (modified by this method). + */ + private final void parseFile(final String fileName, final List<String> columnNames, + final List<List<String>> rows) { + final File inputFile = new File(fileName); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(inputFile)); - String headerLine = reader.readLine(); + final String headerLine = reader.readLine(); if (headerLine == null) { throw new IllegalArgumentException("The file is empty."); } @@ -102,7 +128,7 @@ String line = null; while ((line = reader.readLine()) != null) { tokenizer = new StringTokenizer(line, " \t"); - List<String> row = new ArrayList<String>(); + final List<String> row = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { row.add(tokenizer.nextToken().trim()); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/cli/PrintCommand.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/cli/PrintCommand.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/PrintCommand.java Thu Apr 2 18:14:47 2015 @@ -9,7 +9,9 @@ import java.util.List; import java.util.Set; +import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; import org.hps.conditions.api.ConditionsObject; import org.hps.conditions.api.ConditionsObjectCollection; import org.hps.conditions.api.ConditionsRecord.ConditionsRecordCollection; @@ -17,69 +19,91 @@ import org.hps.conditions.database.TableMetaData; /** - * This sub-command of the conditions CLI prints conditions conditions table data by run number - * to the console or optionally writes it to an output file. - * - * @author Jeremy McCormick <[log in to unmask]> + * This sub-command of the conditions CLI prints conditions conditions table data by run number to the console or + * optionally writes it to an output file. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ class PrintCommand extends AbstractCommand { + + /** + * Print stream for output. + */ + private PrintStream ps = System.out; + + /** + * Flag to print row IDs. + */ + private boolean printIDs = false; + + /** + * Flag to print out column headers. + */ + private boolean printHeaders = true; + + /** + * The field delimiter for print output. + */ + private char fieldDelimiter = ' '; + + /** + * Output file if printing to a file. + */ + private File outputFile; - // By default print to the console. - PrintStream ps = System.out; - - // Print IDs along with field values. - boolean printIDs = false; - - // Print conditions record and table info (default is yes). - boolean printHeaders = true; - - // Field delimited for print out. - char fieldDelimiter = ' '; - - // Output file. - File outputFile; - - DatabaseConditionsManager conditionsManager; - + /** + * Defines command options. + */ + static Options options = new Options(); + static { + options.addOption(new Option("h", false, "Show help for print command")); + options.addOption(new Option("t", true, "Set the table name")); + options.addOption(new Option("i", false, "Print the ID for the records (off by default)")); + options.addOption(new Option("f", true, "Write print output to a file (must be used with -t option)")); + options.addOption(new Option("H", false, "Suppress printing of conditions record and table info")); + options.addOption(new Option("d", false, "Use tabs for field delimiter instead of spaces")); + options.addOption(new Option("T", true, "Specify a conditions tag to use for filtering records")); + } + + /** + * Class constructor. + */ PrintCommand() { - super("print", "Print the table data for a conditions set"); - this.options.addOption(new Option("t", true, "Set the table name")); - this.options.addOption(new Option("i", false, "Print the ID for the records (off by default)")); - this.options.addOption(new Option("f", true, "Write print output to a file (must be used with -t option)")); - this.options.addOption(new Option("H", false, "Suppress printing of conditions record and table info")); - this.options.addOption(new Option("d", false, "Use tabs for field delimiter instead of spaces")); - this.options.addOption(new Option("T", true, "Specify a conditions tag to use for filtering records")); - } - + super("print", "Print the table data for a conditions set", options); + } + /** * Print out the conditions sets selected by the user's command line arguments. - */ - void execute(String[] arguments) { - super.execute(arguments); - - conditionsManager = DatabaseConditionsManager.getInstance(); - + * + * @param arguments The command line arguments. + */ + final void execute(final String[] arguments) { + + final CommandLine commandLine = parse(arguments); + + final DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); + if (!conditionsManager.isInitialized()) { throw new RuntimeException("conditions system is not initialized"); } - + // User specified tag of conditions records. - if (this.commandLine.hasOption("T")) { + if (commandLine.hasOption("T")) { conditionsManager.setTag(commandLine.getOptionValue("T")); } - + // Print conditions sets matching a specific conditions key. String userConditionsKey = null; - if (this.commandLine.hasOption("t")) { - userConditionsKey = this.commandLine.getOptionValue("t"); - } - + if (commandLine.hasOption("t")) { + userConditionsKey = commandLine.getOptionValue("t"); + } + // Setup an output file for the print out if requested. - if (this.commandLine.hasOption("f")) { - if (!this.commandLine.hasOption("t")) { + if (commandLine.hasOption("f")) { + if (!commandLine.hasOption("t")) { throw new IllegalArgumentException("An output file may only be specified when using the -t option."); } - String path = commandLine.getOptionValue("f"); + final String path = commandLine.getOptionValue("f"); if (new File(path).exists()) { throw new IllegalArgumentException("File already exists: " + path); } @@ -89,54 +113,62 @@ } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } - } - + } + // Print IDs in the output. - if (this.commandLine.hasOption("i")) { + if (commandLine.hasOption("i")) { printIDs = true; } - // Print header info. Option turns this off. - if (this.commandLine.hasOption("h")) { + // Print header info. Option turns this off. + if (commandLine.hasOption("h")) { printHeaders = false; } // Use tabs instead of spaces for field delimiter. - if (this.commandLine.hasOption("d")) { + if (commandLine.hasOption("d")) { fieldDelimiter = '\t'; } - - // List of conditions records to print. - ConditionsRecordCollection conditionsRecords = new ConditionsRecordCollection(); - + + // List of conditions records to print. + final ConditionsRecordCollection conditionsRecords = new ConditionsRecordCollection(); + // Did the user specify a table to use? if (userConditionsKey == null) { System.out.println("printing all conditions"); // Use all table names if there was not one specified. conditionsRecords.addAll(conditionsManager.getConditionsRecords()); - } else { + } else { System.out.println("printing conditions with name: " + userConditionsKey); // Get records only for the user specified table name. conditionsRecords.addAll(conditionsManager.findConditionsRecords(userConditionsKey)); } - + // Sort the records by key (table name). conditionsRecords.sortByKey(); - + // Get a unique list of keys from the returned conditions records. - Set<String> conditionsKeys = conditionsRecords.getConditionsKeys(); - + final Set<String> conditionsKeys = conditionsRecords.getConditionsKeys(); + // Print the records and the data. - printConditionsRecords(conditionsKeys); - ps.flush(); + printConditionsRecords(conditionsKeys); + ps.flush(); ps.close(); - + if (outputFile != null) { System.out.println("wrote collection data to file " + outputFile.getPath()); } } - private void printConditionsRecords(Set<String> conditionsKeys) { + /** + * Print out the conditions records either to the console or a file (if that option is enabled). + * + * @param conditionsKeys The list of conditions keys (usually same as table names). + */ + private void printConditionsRecords(final Set<String> conditionsKeys) { + + final DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); + System.out.print("printing conditions sets: "); for (String conditionsKey : conditionsKeys) { System.out.print(conditionsKey + " "); @@ -144,31 +176,35 @@ System.out.println(); // Loop over the conditions keys from the conditions records. for (String conditionsKey : conditionsKeys) { - + // The list of collections to print. - List<ConditionsObjectCollection<?>> collectionList = new ArrayList<ConditionsObjectCollection<?>>(); - + final List<ConditionsObjectCollection<?>> collectionList = new ArrayList<ConditionsObjectCollection<?>>(); + // Get the table meta data for the conditions key. - TableMetaData tableMetaData = conditionsManager.findTableMetaData(conditionsKey); - + final TableMetaData tableMetaData = conditionsManager.findTableMetaData(conditionsKey); + // This shouldn't ever happen but check anyways. - if (tableMetaData == null) { - throw new RuntimeException("The table meta data for " + conditionsKey + " does not exist. The key might be invalid."); - } - + if (tableMetaData == null) { + throw new RuntimeException("The table meta data for " + conditionsKey + + " does not exist. The key might be invalid."); + } + // Use only the single collection which would be seen by a user job for this run number and key. - ConditionsObjectCollection<?> collection = conditionsManager.getCachedConditions( - tableMetaData.getCollectionClass(), - tableMetaData.getTableName()).getCachedData(); - + final ConditionsObjectCollection<?> collection = conditionsManager.getCachedConditions( + tableMetaData.getCollectionClass(), tableMetaData.getTableName()).getCachedData(); + collectionList.add(collection); - + // Print out all the collection data to console or file. printCollections(collectionList); } } - private void printCollections(List<ConditionsObjectCollection<?>> collectionList) { + /** + * Print the list of collections. + * @param collectionList The list of collections. + */ + private void printCollections(final List<ConditionsObjectCollection<?>> collectionList) { // Loop over all the collections and print them. for (ConditionsObjectCollection<?> collection : collectionList) { if (printHeaders) { @@ -177,15 +213,19 @@ printColumnNames(collection.getTableMetaData()); printCollection(collection); System.out.println(); - } + } ps.flush(); } - private void printCollection(ConditionsObjectCollection<?> collection) { - StringBuffer buffer = new StringBuffer(); + /** + * Print a single collection. + * @param collection The collection. + */ + private void printCollection(final ConditionsObjectCollection<?> collection) { + final StringBuffer buffer = new StringBuffer(); for (Object object : collection) { for (String columnName : collection.getTableMetaData().getFieldNames()) { - buffer.append(((ConditionsObject)object).getFieldValue(columnName)); + buffer.append(((ConditionsObject) object).getFieldValue(columnName)); buffer.append(fieldDelimiter); } buffer.setLength(buffer.length() - 1); @@ -196,7 +236,11 @@ ps.flush(); } - private void printCollectionHeader(ConditionsObjectCollection<?> collection) { + /** + * Print the header for a collection. + * @param collection The collection. + */ + private void printCollectionHeader(final ConditionsObjectCollection<?> collection) { System.out.println("--------------------------------------"); System.out.print(collection.getConditionsRecord()); System.out.println("--------------------------------------"); @@ -204,11 +248,15 @@ System.out.flush(); } - private void printColumnNames(TableMetaData tableMetaData) { + /** + * Print the column names. + * @param tableMetaData The table meta data. + */ + private void printColumnNames(final TableMetaData tableMetaData) { if (printIDs) { ps.print("id"); ps.print(fieldDelimiter); - } + } for (String columnName : tableMetaData.getFieldNames()) { ps.print(columnName); ps.print(fieldDelimiter); Added: java/trunk/conditions/src/main/java/org/hps/conditions/cli/package-info.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/cli/package-info.java (added) +++ java/trunk/conditions/src/main/java/org/hps/conditions/cli/package-info.java Thu Apr 2 18:14:47 2015 @@ -0,0 +1,6 @@ +/** + * Command line interface to the conditions system. + * + * @author Jeremy McCormick <[log in to unmask]> + */ +package org.hps.conditions.cli; Copied: java/trunk/conditions/src/main/java/org/hps/conditions/database/AbstractConditionsObjectConverter.java (from r2659, java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsObjectConverter.java) ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsObjectConverter.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/AbstractConditionsObjectConverter.java Thu Apr 2 18:14:47 2015 @@ -4,7 +4,7 @@ import java.sql.ResultSetMetaData; import java.sql.SQLException; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.api.ConditionsObject; import org.hps.conditions.api.ConditionsObjectCollection; import org.hps.conditions.api.ConditionsObjectException; @@ -16,56 +16,66 @@ /** * <p> - * Implementation of default conversion from database tables to a - * {@link ConditionsObject} class. + * Implementation of default conversion from database tables to a {@link ConditionsObject} class. * <p> * This class actually returns collections and not individual objects. - * - * @author Jeremy McCormick <[log in to unmask]> - * - * @param <T> The type of the returned data which should be a class extending {@link AbstractConditionsObjectCollection}. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> + * @param <T> The type of the returned data which should be a class extending {@link BaseConditionsObjectCollection}. */ -public abstract class ConditionsObjectConverter<T> implements ConditionsConverter<T> { - - MultipleCollectionsAction multipleCollections; - - public ConditionsObjectConverter() { - } - - /** - * Set the action that the converter will use to disambiguate when multiple - * conditions sets are found. +public abstract class AbstractConditionsObjectConverter<T> implements ConditionsConverter<T> { + + /** + * The action to take if multiple overlapping conditions sets are found. + * The default is using the most recently updated one. + */ + private MultipleCollectionsAction multipleCollections = MultipleCollectionsAction.LAST_UPDATED; + + /** + * Class constructor. + */ + public AbstractConditionsObjectConverter() { + } + + /** + * Set the action that the converter will use to disambiguate when multiple conditions sets are found. + * * @param multipleCollections The multiple collections action. */ - void setMultipleCollectionsAction(MultipleCollectionsAction multipleCollections) { + final void setMultipleCollectionsAction(MultipleCollectionsAction multipleCollections) { this.multipleCollections = multipleCollections; } - - /** + + /** * Get the multiple collections action. + * * @return The multiple collections action. */ - public MultipleCollectionsAction getMultipleCollectionsAction() { + public final MultipleCollectionsAction getMultipleCollectionsAction() { return this.multipleCollections; } - + /** * Get the specific type converted by this class. + * * @return The class that this converter handles. */ public abstract Class<T> getType(); /** - * Get the conditions data based on the name, e.g. "ecal_channels". - * The table information is found using the type handled by the Converter. + * Get the conditions data based on the name, e.g. "ecal_channels". The table information is found using the type + * handled by the Converter. + * + * @param conditionsManager The current conditions manager. + * @param name The name of the conditions set (maps to table name). * @return The conditions data. */ @SuppressWarnings({ "unchecked", "rawtypes" }) - public T getData(ConditionsManager conditionsManager, String name) { - + public T getData(final ConditionsManager conditionsManager, final String name) { + // Get the DatabaseConditionsManager which is required for using this converter. - DatabaseConditionsManager databaseConditionsManager = (DatabaseConditionsManager) conditionsManager; - + final DatabaseConditionsManager databaseConditionsManager = (DatabaseConditionsManager) conditionsManager; + // Setup connection if necessary. boolean reopenedConnection = false; if (!databaseConditionsManager.isConnected()) { @@ -73,21 +83,21 @@ databaseConditionsManager.openConnection(); reopenedConnection = true; } - + // Get the TableMetaData from the table name. - TableMetaData tableMetaData = databaseConditionsManager.findTableMetaData(name); - + final TableMetaData tableMetaData = databaseConditionsManager.findTableMetaData(name); + // Throw an exception if the table name does not map to a known type. if (tableMetaData == null) { throw new RuntimeException(new ConditionsObjectException("No table information found for name: " + name)); } - + // Get the ConditionsRecordCollection with the run number assignments. - ConditionsRecordCollection conditionsRecords = databaseConditionsManager.findConditionsRecords(name); - + final ConditionsRecordCollection conditionsRecords = databaseConditionsManager.findConditionsRecords(name); + // The record with the collection information. ConditionsRecord conditionsRecord = null; - + // Now we need to determine which ConditionsRecord object to use. if (conditionsRecords.size() == 0) { // No conditions records were found for the key. @@ -96,22 +106,22 @@ } else if (conditionsRecords.size() == 1) { // Use the single conditions set that was found. conditionsRecord = conditionsRecords.get(0); - } else if (conditionsRecords.size() > 1) { + } else if (conditionsRecords.size() > 1) { if (multipleCollections.equals(MultipleCollectionsAction.LAST_UPDATED)) { // Use the conditions set with the latest updated date. conditionsRecord = conditionsRecords.sortedByUpdated().get(conditionsRecords.size() - 1); - } else if (multipleCollections.equals(MultipleCollectionsAction.LAST_CREATED)){ + } else if (multipleCollections.equals(MultipleCollectionsAction.LAST_CREATED)) { // Use the conditions set with the latest created date. conditionsRecord = conditionsRecords.sortedByCreated().get(conditionsRecords.size() - 1); } else if (multipleCollections.equals(MultipleCollectionsAction.LATEST_RUN_START)) { // Use the conditions set with the greatest run start value. conditionsRecord = conditionsRecords.sortedByRunStart().get(conditionsRecords.size() - 1); - } else if (multipleCollections.equals(MultipleCollectionsAction.ERROR)) { + } else if (multipleCollections.equals(MultipleCollectionsAction.ERROR)) { // The converter has been configured to throw an error. throw new RuntimeException("Multiple ConditionsRecord object found for conditions key " + name); - } - } - + } + } + // Create a collection of objects to return. ConditionsObjectCollection collection = null; try { @@ -121,24 +131,24 @@ } DatabaseConditionsManager.getLogger().info("loading conditions set..." + '\n' + conditionsRecord); - + // Get the table name. - String tableName = conditionsRecord.getTableName(); + final String tableName = conditionsRecord.getTableName(); // Get the collection ID. - int collectionId = conditionsRecord.getCollectionId(); + final int collectionId = conditionsRecord.getCollectionId(); // Build a select query. - String query = QueryBuilder.buildSelect(tableName, collectionId, tableMetaData.getFieldNames(), "id ASC"); + final String query = QueryBuilder.buildSelect(tableName, collectionId, tableMetaData.getFieldNames(), "id ASC"); // Query the database to get the collection's rows. - ResultSet resultSet = databaseConditionsManager.selectQuery(query); + final ResultSet resultSet = databaseConditionsManager.selectQuery(query); try { // Loop over the rows. while (resultSet.next()) { // Create a new ConditionsObject from this row. - ConditionsObject newObject = createConditionsObject(resultSet, tableMetaData); + final ConditionsObject newObject = createConditionsObject(resultSet, tableMetaData); // Add the object to the collection. collection.add(newObject); @@ -150,28 +160,30 @@ // Close the Statement and the ResultSet. DatabaseUtilities.cleanup(resultSet); - + if (reopenedConnection) { // Close connection if one was opened. databaseConditionsManager.closeConnection(); } - + return (T) collection; } - + /** * Create a conditions object. + * * @param resultSet The database record. * @param tableMetaData The table data for the object. * @return The conditions object. * @throws SQLException If there is a problem using the database. */ - static final ConditionsObject createConditionsObject(ResultSet resultSet, TableMetaData tableMetaData) throws SQLException { - ResultSetMetaData metaData = resultSet.getMetaData(); - int rowId = resultSet.getInt(1); - int ncols = metaData.getColumnCount(); + static final ConditionsObject createConditionsObject(final ResultSet resultSet, final TableMetaData tableMetaData) + throws SQLException { + final ResultSetMetaData metaData = resultSet.getMetaData(); + final int rowId = resultSet.getInt(1); + final int nCols = metaData.getColumnCount(); FieldValueMap fieldValues = new FieldValueMap(); - for (int i = 2; i <= ncols; i++) { + for (int i = 2; i <= nCols; i++) { fieldValues.put(metaData.getColumnName(i), resultSet.getObject(i)); } ConditionsObject newObject = null; @@ -181,38 +193,44 @@ throw new RuntimeException(e); } try { - newObject.setRowId(rowId); + newObject.setRowID(rowId); } catch (ConditionsObjectException e) { throw new RuntimeException(e); } newObject.setFieldValues(fieldValues); return newObject; } - + /** * Create a conditions object collection. - * @param conditionsRecord The conditions record. + * + * @param conditionsRecord The conditions record. * @param tableMetaData The table data. * @return The conditions object collection. * @throws ConditionsObjectException If there is a problem creating the collection. */ - static final AbstractConditionsObjectCollection<?> createCollection(ConditionsRecord conditionsRecord, TableMetaData tableMetaData) throws ConditionsObjectException { - AbstractConditionsObjectCollection<?> collection; + static final BaseConditionsObjectCollection<?> createCollection(final ConditionsRecord conditionsRecord, + final TableMetaData tableMetaData) throws ConditionsObjectException { + BaseConditionsObjectCollection<?> collection; try { collection = tableMetaData.getCollectionClass().newInstance(); if (conditionsRecord != null) { collection.setConditionsRecord(conditionsRecord); collection.setTableMetaData(tableMetaData); - collection.setCollectionId(conditionsRecord.getCollectionId()); + collection.setCollectionID(conditionsRecord.getCollectionId()); } } catch (InstantiationException | IllegalAccessException e) { throw new ConditionsObjectException("Error creating conditions object collection.", e); } return collection; - } - + } + + /** + * Convert to string. + * @return The string. + */ public String toString() { - return "ConditionsObjectConverter: type = " + this.getType() + - ", multipleCollectionsAction = " + this.getMultipleCollectionsAction().toString(); + return "ConditionsObjectConverter: type = " + this.getType() + ", multipleCollectionsAction = " + + this.getMultipleCollectionsAction().toString(); } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsRecordConverter.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsRecordConverter.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsRecordConverter.java Thu Apr 2 18:14:47 2015 @@ -3,47 +3,50 @@ import java.sql.ResultSet; import java.sql.SQLException; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.api.ConditionsObject; import org.hps.conditions.api.ConditionsRecord.ConditionsRecordCollection; import org.lcsim.conditions.ConditionsManager; /** - * Read ConditionsRecord objects from the conditions database and cache the conditions set. - * @author Jeremy McCormick <[log in to unmask]> + * Read {@link org.hps.conditions.api.ConditionsRecord} objects from the conditions database. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -public class ConditionsRecordConverter extends ConditionsObjectConverter<ConditionsRecordCollection> { +public final class ConditionsRecordConverter extends AbstractConditionsObjectConverter<ConditionsRecordCollection> { /** - * Get the ConditionsRecords for a run based on current configuration of the - * <code>DatabaseConditionsManager</code>. + * Get the ConditionsRecords for a run based on current configuration of the conditions system. + * * @param manager The current conditions manager. * @param name The name of the conditions set. * @return The matching ConditionsRecords. */ @SuppressWarnings({ "unchecked", "rawtypes" }) - public ConditionsRecordCollection getData(ConditionsManager manager, String name) { + public ConditionsRecordCollection getData(final ConditionsManager manager, final String name) { - DatabaseConditionsManager databaseConditionsManager = DatabaseConditionsManager.getInstance(); - + final DatabaseConditionsManager databaseConditionsManager = DatabaseConditionsManager.getInstance(); + // Setup connection if necessary. boolean reopenedConnection = false; if (!databaseConditionsManager.isConnected()) { databaseConditionsManager.openConnection(); reopenedConnection = true; } - - TableMetaData tableMetaData = databaseConditionsManager.findTableMetaData(name); - if (tableMetaData == null) + final TableMetaData tableMetaData = databaseConditionsManager.findTableMetaData(name); + + if (tableMetaData == null) { throw new RuntimeException("Failed to find meta data with key " + name); + } - String query = "SELECT * from " + tableMetaData.getTableName() + " WHERE " + "run_start <= " + manager.getRun() + " AND run_end >= " + manager.getRun(); + final String query = "SELECT * from " + tableMetaData.getTableName() + " WHERE " + "run_start <= " + + manager.getRun() + " AND run_end >= " + manager.getRun(); - ResultSet resultSet = databaseConditionsManager.selectQuery(query); + final ResultSet resultSet = databaseConditionsManager.selectQuery(query); // Create a collection to return. - AbstractConditionsObjectCollection collection; + BaseConditionsObjectCollection collection; try { collection = tableMetaData.getCollectionClass().newInstance(); } catch (InstantiationException | IllegalAccessException e) { @@ -52,29 +55,30 @@ try { while (resultSet.next()) { - ConditionsObject conditionsRecord = ConditionsObjectConverter.createConditionsObject(resultSet, tableMetaData); + final ConditionsObject conditionsRecord = AbstractConditionsObjectConverter.createConditionsObject(resultSet, + tableMetaData); collection.add(conditionsRecord); } } catch (SQLException x) { throw new RuntimeException("Database error", x); } - + // Close the ResultSet and Statement. DatabaseUtilities.cleanup(resultSet); - + if (reopenedConnection) { databaseConditionsManager.closeConnection(); } - + return getType().cast(collection); } /** * Get the type handled by this converter. - * @return The type handled by this converter, which is - * <code>ConditionsRecordCollection</code>. + * + * @return The type handled by this converter, which is <code>ConditionsRecordCollection</code>. */ public Class<ConditionsRecordCollection> getType() { return ConditionsRecordCollection.class; } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsSeriesConverter.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsSeriesConverter.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/ConditionsSeriesConverter.java Thu Apr 2 18:14:47 2015 @@ -12,27 +12,39 @@ /** * This converter creates a {@link org.hps.conditions.api.ConditionsSeries} which is a list of - * {@link org.hps.conditions.api.ConditionsObjectCollection} objects having the same type. + * {@link org.hps.conditions.api.ConditionsObjectCollection} objects having the same type. * This can be used to retrieve sets of conditions that may overlap in time validity. The user * may then use whichever collections are of interest to them. - * + * * @see org.hps.conditions.api.ConditionsSeries * @see org.hps.conditions.api.ConditionsObjectCollection * @see org.hps.conditions.api.ConditionsObject * @see DatabaseConditionsManager - * + * * @param <ObjectType> The type of the ConditionsObject. * @param <CollectionType> The type of the collection. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -// FIXME: The ObjectType and CollectionType should probably not extend in order to simplify the types. -class ConditionsSeriesConverter<ObjectType extends ConditionsObject, CollectionType extends ConditionsObjectCollection<ObjectType>> { +final class ConditionsSeriesConverter<ObjectType extends ConditionsObject, + CollectionType extends ConditionsObjectCollection<ObjectType>> { - Class<ObjectType> objectType; - Class<CollectionType> collectionType; - - ConditionsSeriesConverter(Class<ObjectType> objectType, Class<CollectionType> collectionType) { + /** + * The type of the object. + */ + final Class<ObjectType> objectType; + + /** + * The type of the collection. + */ + final Class<CollectionType> collectionType; + + /** + * Class constructor. + * @param objectType The type of the object. + * @param collectionType The type of the collection. + */ + ConditionsSeriesConverter(final Class<ObjectType> objectType, final Class<CollectionType> collectionType) { this.collectionType = collectionType; this.objectType = objectType; } @@ -41,59 +53,62 @@ * Create a new conditions series. * @param tableName The name of the data table. * @return The conditions series. - */ + */ @SuppressWarnings({ "unchecked" }) - ConditionsSeries<ObjectType, CollectionType> createSeries(String tableName) { + final ConditionsSeries<ObjectType, CollectionType> createSeries(final String tableName) { if (tableName == null) { throw new IllegalArgumentException("The tableName argument is null."); } - - DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); - + + final DatabaseConditionsManager conditionsManager = DatabaseConditionsManager.getInstance(); + // Setup connection if necessary. boolean reopenedConnection = false; if (!conditionsManager.isConnected()) { conditionsManager.openConnection(); reopenedConnection = true; } - + // Get the table meta data for the collection type. - TableMetaData tableMetaData = conditionsManager.findTableMetaData(tableName); + final TableMetaData tableMetaData = conditionsManager.findTableMetaData(tableName); if (tableMetaData == null) { throw new RuntimeException("Table meta data for " + collectionType + " was not found."); } // Create a new conditions series. - ConditionsSeries<ObjectType, CollectionType> series = new ConditionsSeries<ObjectType, CollectionType>(objectType, collectionType); - + final ConditionsSeries<ObjectType, CollectionType> series = + new ConditionsSeries<ObjectType, CollectionType>(); + // Get the ConditionsRecord with the meta-data, which will use the current run number from the manager. - ConditionsRecordCollection conditionsRecords = conditionsManager.findConditionsRecords(tableName); + final ConditionsRecordCollection conditionsRecords = conditionsManager.findConditionsRecords(tableName); for (ConditionsRecord conditionsRecord : conditionsRecords) { ConditionsObjectCollection<ObjectType> collection; try { - collection = (ConditionsObjectCollection<ObjectType>) + collection = (ConditionsObjectCollection<ObjectType>) ConditionsRecordConverter.createCollection(conditionsRecord, tableMetaData); } catch (ConditionsObjectException e) { throw new RuntimeException(e); } // Get the collection ID. - int collectionId = conditionsRecord.getCollectionId(); + final int collectionId = conditionsRecord.getCollectionId(); // Build a select query. - String query = QueryBuilder.buildSelect(tableName, collectionId, tableMetaData.getFieldNames(), "id ASC"); + final String query = QueryBuilder.buildSelect(tableName, collectionId, + tableMetaData.getFieldNames(), "id ASC"); // Query the database. - ResultSet resultSet = conditionsManager.selectQuery(query); + final ResultSet resultSet = conditionsManager.selectQuery(query); try { // Loop over rows. while (resultSet.next()) { // Create new ConditionsObject. - ConditionsObject newObject = ConditionsRecordConverter.createConditionsObject(resultSet, tableMetaData); + final ConditionsObject newObject = + ConditionsRecordConverter.createConditionsObject(resultSet, tableMetaData); // Add new object to collection. collection.add((ObjectType) newObject); @@ -103,14 +118,14 @@ } DatabaseUtilities.cleanup(resultSet); - + series.add((CollectionType) collection); } - + if (reopenedConnection) { conditionsManager.closeConnection(); } - + // Return new collection. return series; } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/ConnectionParameters.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/ConnectionParameters.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/ConnectionParameters.java Thu Apr 2 18:14:47 2015 @@ -11,20 +11,41 @@ import java.util.Properties; /** - * This class encapsulates the parameters for connecting to a database, - * including hostname, port, user and password. It can also create and return a - * Connection object based on these parameters. - * @author Jeremy McCormick <[log in to unmask]> + * This class encapsulates the parameters for connecting to a database, including host name, port, user and password. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -public class ConnectionParameters { - +public final class ConnectionParameters { + + /** + * The default port number. + */ public static final int DEFAULT_PORT = 3306; - - protected String user; - protected String password; - protected int port; - protected String hostname; - protected String database; + + /** + * The user name. + */ + private String user; + + /** + * The user's password. + */ + private String password; + + /** + * The port. + */ + private int port; + + /** + * The host name. + */ + private String hostname; + + /** + * The database name. + */ + private String database; /** * Protected constructor for sub-classes. @@ -34,13 +55,15 @@ /** * Fully qualified constructor. + * * @param user The user name. * @param password The password. * @param hostname The hostname. * @param port The port number. * @param conditionsTable The table containing conditions validity data. */ - public ConnectionParameters(String user, String password, String database, String hostname, int port) { + public ConnectionParameters(final String user, final String password, final String database, final String hostname, + final int port) { this.user = user; this.password = password; this.database = database; @@ -50,10 +73,11 @@ /** * Get Properties object for this connection. + * * @return The Properties for this connection. */ public Properties getConnectionProperties() { - Properties p = new Properties(); + final Properties p = new Properties(); p.put("user", user); p.put("password", password); return p; @@ -61,14 +85,16 @@ /** * Get the hostname. + * * @return The hostname. */ - String getHostname() { + final String getHostname() { return hostname; } /** * Get the port number. + * * @return The port number. */ int getPort() { @@ -77,6 +103,7 @@ /** * Get the name of the database. + * * @return The name of the database. */ String getDatabase() { @@ -85,6 +112,8 @@ /** * Get the user name. + * + * @return The user name. */ String getUser() { return user; @@ -92,6 +121,8 @@ /** * Get the password. + * + * @return The password. */ String getPassword() { return password; @@ -99,19 +130,21 @@ /** * Get the connection string for these parameters. + * * @return The connection string. */ - public String getConnectionString() { + String getConnectionString() { return "jdbc:mysql://" + hostname + ":" + port + "/"; } /** - * Create a database connection from these parameters. The caller becomes - * the "owner" and is responsible for closing it when finished. + * Create a database connection from these parameters. The caller becomes the "owner" and is responsible for closing + * it when finished. + * * @return The Connection object. */ public Connection createConnection() { - Properties connectionProperties = getConnectionProperties(); + final Properties connectionProperties = getConnectionProperties(); Connection connection = null; try { connection = DriverManager.getConnection(getConnectionString(), connectionProperties); @@ -124,10 +157,11 @@ /** * Configure the connection parameters from a properties file. + * * @param file The properties file. * @return The connection parameters. */ - public static final ConnectionParameters fromProperties(File file) { + public static final ConnectionParameters fromProperties(final File file) { FileInputStream fin = null; try { fin = new FileInputStream(file); @@ -138,33 +172,33 @@ } /** - * Configure the connection parameters from an embedded classpath resource - * which should be a properties file. - * @param String The resource path. + * Configure the connection parameters from an embedded classpath resource which should be a properties file. + * + * @param resource The resource path. * @return The connection parameters. */ - public static final ConnectionParameters fromResource(String resource) { + public static ConnectionParameters fromResource(final String resource) { return fromProperties(ConnectionParameters.class.getResourceAsStream(resource)); } /** - * Configure the connection parameters from an <code>InputStream</code> of - * properties. + * Configure the connection parameters from an <code>InputStream</code> of properties. + * * @param in The InputStream of the properties. * @return The connection parameters. * @throws RuntimeException if the InputStream is invalid */ - private static final ConnectionParameters fromProperties(InputStream in) { - Properties properties = new Properties(); + private static ConnectionParameters fromProperties(final InputStream in) { + final Properties properties = new Properties(); try { properties.load(in); } catch (IOException e) { throw new RuntimeException(e); } - String user = properties.getProperty("user"); - String password = properties.getProperty("password"); - String database = properties.getProperty("database"); - String hostname = properties.getProperty("hostname"); + final String user = properties.getProperty("user"); + final String password = properties.getProperty("password"); + final String database = properties.getProperty("database"); + final String hostname = properties.getProperty("hostname"); int port = DEFAULT_PORT; if (properties.containsKey("port")) { port = Integer.parseInt(properties.getProperty("port")); Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/Converter.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/Converter.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/Converter.java Thu Apr 2 18:14:47 2015 @@ -6,25 +6,27 @@ import java.lang.annotation.Target; /** - * Annotation for providing converter configuration for {@link org.hps.conditions.api.ConditionsObject} classes. - * - * @see ConditionsObjectConverter - * - * @author Jeremy McCormick <[log in to unmask]> + * This is an annotation for providing converter configuration for {@link org.hps.conditions.api.ConditionsObject} + * classes. + * + * @see AbstractConditionsObjectConverter + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) +@Target(ElementType.TYPE) public @interface Converter { /** - * Get the action to perform in the converter when multiple conditions are found for the current configuration - * of run number, detector and tag in the manager. + * Get the action to perform in the converter when multiple conditions are found for the current configuration of + * run number, detector and tag in the manager. + * * @return The multiple collections action. */ MultipleCollectionsAction multipleCollectionsAction() default MultipleCollectionsAction.ERROR; - + /** - * Get a custom converter class for the type. (Optional) + * Get a custom converter class for the type. (Optional) + * * @return The custom converter for the type. */ - Class<?> converter() default ConditionsObjectConverter.class; + Class<?> converter() default AbstractConditionsObjectConverter.class; } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/ConverterRegistry.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/ConverterRegistry.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/ConverterRegistry.java Thu Apr 2 18:14:47 2015 @@ -1,42 +1,45 @@ package org.hps.conditions.database; import java.util.HashMap; +import java.util.Map.Entry; import java.util.Set; -import java.util.Map.Entry; import javassist.Modifier; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.api.ConditionsObject; import org.hps.conditions.api.ConditionsObjectUtilities; import org.reflections.Reflections; /** - * This is a registry of all available conditions converters. - * These classes are found using reflection. An anonymous converter - * is created on the fly for {@link org.hps.conditions.api.ConditionsObject} - * classes with a {@link Table}, and the class itself must not be abstract. - * If the {@link Converter} annotation is set on the class, then this - * is used to instantiate the specific converter class instead. - * - * @see ConditionsObjectConverter - * - * @author Jeremy McCormick <[log in to unmask]> + * This is a registry of all available conditions converters. These classes are found using reflection. An anonymous + * converter is created on the fly for {@link org.hps.conditions.api.ConditionsObject} classes with a {@link Table}, and + * the class itself must not be abstract. If the {@link Converter} annotation is set on the class, then this is used to + * instantiate the specific converter class instead. + * + * @see AbstractConditionsObjectConverter + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -public class ConverterRegistry extends HashMap<Class<? extends ConditionsObject>, ConditionsObjectConverter> { - +@SuppressWarnings("serial") +public final class ConverterRegistry extends HashMap<Class<? extends ConditionsObject>, AbstractConditionsObjectConverter> { + + /** + * Class should not be instantiated by users. + * The {@link #create()} method should be used instead. + */ private ConverterRegistry() { } - + /** - * Automatically create converters for all conditions object classes. + * Automatically create converters for all {@link org.hps.conditions.api.ConditionsObject} classes. + * * @return The registry of converters. */ @SuppressWarnings({ "unchecked", "rawtypes" }) static ConverterRegistry create() { - ConverterRegistry registry = new ConverterRegistry(); - Reflections reflections = new Reflections("org.hps.conditions"); - Set<Class<? extends ConditionsObject>> objectTypes = reflections.getSubTypesOf(ConditionsObject.class); + final ConverterRegistry registry = new ConverterRegistry(); + final Reflections reflections = new Reflections("org.hps.conditions"); + final Set<Class<? extends ConditionsObject>> objectTypes = reflections.getSubTypesOf(ConditionsObject.class); for (Class<? extends ConditionsObject> objectType : objectTypes) { if (Modifier.isAbstract(objectType.getModifiers())) { continue; @@ -46,20 +49,20 @@ } MultipleCollectionsAction multipleCollectionsAction = MultipleCollectionsAction.ERROR; Class<?> converterClass = null; - Converter converterAnnotation = objectType.getAnnotation(Converter.class); + final Converter converterAnnotation = objectType.getAnnotation(Converter.class); if (converterAnnotation != null) { multipleCollectionsAction = converterAnnotation.multipleCollectionsAction(); - if (!converterAnnotation.converter().equals(ConditionsObjectConverter.class)) { + if (!converterAnnotation.converter().equals(AbstractConditionsObjectConverter.class)) { converterClass = converterAnnotation.converter(); } } - - final Class<? extends AbstractConditionsObjectCollection<? extends ConditionsObject>> collectionType = - ConditionsObjectUtilities.getCollectionType(objectType); - - ConditionsObjectConverter converter = null; + + final Class<? extends BaseConditionsObjectCollection<? extends ConditionsObject>> + collectionType = ConditionsObjectUtilities.getCollectionType(objectType); + + AbstractConditionsObjectConverter converter = null; if (converterClass == null) { - converter = new ConditionsObjectConverter() { + converter = new AbstractConditionsObjectConverter() { @Override public Class getType() { return collectionType; @@ -68,23 +71,29 @@ } else { try { Object object = converterClass.newInstance(); - if (!(object instanceof ConditionsObjectConverter)) { - throw new RuntimeException("The Converter has the wrong type: " + object.getClass().getCanonicalName()); + if (!(object instanceof AbstractConditionsObjectConverter)) { + throw new RuntimeException("The Converter has the wrong type: " + + object.getClass().getCanonicalName()); } - converter = (ConditionsObjectConverter) object; + converter = (AbstractConditionsObjectConverter) object; } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } converter.setMultipleCollectionsAction(multipleCollectionsAction); registry.put(converter.getType(), converter); - } + } return registry; } - - public String toString() { - StringBuffer buff = new StringBuffer(); - for (Entry<Class<? extends ConditionsObject>, ConditionsObjectConverter> entry : entrySet()) { + + /** + * Convert the object to a string. + * @return The object converted to a string. + */ + @SuppressWarnings("rawtypes") + public final String toString() { + final StringBuffer buff = new StringBuffer(); + for (Entry<Class<? extends ConditionsObject>, AbstractConditionsObjectConverter> entry : entrySet()) { buff.append(entry.getValue().toString()); } return buff.toString(); Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseConditionsManager.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseConditionsManager.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseConditionsManager.java Thu Apr 2 18:14:47 2015 @@ -47,142 +47,232 @@ /** * <p> - * This class provides the top-level API for accessing database conditions, - * as well as configuring the database connection, initializing all - * required components, and loading required converters and table meta data. - * It is registered as the global <code>ConditionsManager</code> in the - * constructor. + * This class provides the top-level API for accessing database conditions, as well as configuring the database + * connection, initializing all required components, and loading required converters and table meta data. It is + * registered as the global <code>ConditionsManager</code> in the constructor. * <p> - * Differences between Test Run and Engineering Run configurations are handled - * automatically. - * + * Differences between Test Run and Engineering Run configurations are handled automatically. + * * @see org.lcsim.conditions.ConditionsManager - * - * @author Jeremy McCormick <[log in to unmask]> + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @SuppressWarnings("rawtypes") public final class DatabaseConditionsManager extends ConditionsManagerImplementation { - // Initialize logger. - private static Logger logger = LogUtil.create(DatabaseConditionsManager.class.getName(), new DefaultLogFormatter(), Level.FINE); - - // Global registry of conditions converters. + /** + * Initialize the logger. + */ + private static Logger logger = LogUtil.create(DatabaseConditionsManager.class.getName(), new DefaultLogFormatter(), + Level.FINE); + + /** + * Create the global registry of conditions object converters. + */ private ConverterRegistry converters = ConverterRegistry.create(); - - // Global registry of table meta data. + + /** + * Create the global registry of table meta data. + */ private TableRegistry tableRegistry = TableRegistry.create(); - - // Connection configuration. + + /** + * Name of system property that can be used to specify custom database connection parameters. + */ private static final String CONNECTION_PROPERTY = "org.hps.conditions.connection.file"; + + /** + * The connection properties file, if one is being used from the command line. + */ private File connectionPropertiesFile; + + /** + * The current connection parameters. + */ private ConnectionParameters connectionParameters; + + /** + * The current database connection. + */ private Connection connection; + + /** + * True if manager is connected to the database. + */ private boolean isConnected = false; + + /** + * Flag used to print connection parameters one time. + */ private boolean loggedConnectionParameters = false; - - // Default configuration resources. + + /** + * The default XML config. + */ private static final String DEFAULT_CONFIG = "/org/hps/conditions/config/conditions_database_prod.xml"; + + /** + * The Test Run XML config. + */ private static final String TEST_RUN_CONFIG = "/org/hps/conditions/config/conditions_database_testrun_2012.xml"; + + /** + * The Eng Run XML config. + */ private static final String ENGRUN_CONFIG = "/org/hps/conditions/config/conditions_database_engrun.xml"; - - // Default connection properties resource. + + /** + * The connection properties resource for connecting to the default JLAB database. + */ private static final String DEFAULT_CONNECTION_PROPERTIES_RESOURCE = "/org/hps/conditions/config/jlab_connection.prop"; - - // Max run number for the Test Run. + + /** + * The max value for a run to be considered Test Run. + */ private static final int TEST_RUN_MAX_RUN = 1365; - - // Detector setup. + + /** + * The default ECAL detector name in the detector geometry. + */ private String ecalName = "Ecal"; + + /** + * The default SVT name in the detector geometry. + */ private String svtName = "Tracker"; + + /** + * The converter for creating the combined SVT conditions object. + */ private ConditionsConverter svtConverter; + + /** + * The converter for creating the combined ECAL conditions object. + */ private ConditionsConverter ecalConverter; + + /** + * The helper for setting up the SVT detector with its conditions information. + */ private SvtDetectorSetup svtSetup = new SvtDetectorSetup(svtName); - - // Active conditions tag. + + /** + * The currently active conditions tag. + */ private String tag = null; - // State of manager. + /** + * True if the manager has been initialized, e.g. the {@link #setDetector(String, int)} method was called. + */ private boolean isInitialized = false; + + /** + * True if the conditions system has been frozen and will ignore updates after it is initialized. + */ private boolean isFrozen = false; + + /** + * True if the conditions manager was configured from an XML configuration resource or file. + */ private boolean isConfigured = false; - - // Configuration from XML settings. These are the defaults. + + /** + * True to setup the SVT detector model with conditions. + */ private boolean setupSvtDetector = true; + + /** + * True to freeze the system after initialization. + */ private boolean freezeAfterInitialize = false; + + /** + * True to close the connection after initialization. + */ private boolean closeConnectionAfterInitialize = true; + + /** + * True to cache all known conditions sets (from keys) during initialization. + */ private boolean cacheAllConditions = false; + + /** + * True if current run number is from Test Run. + */ private boolean isTestRun = false; - + static { - // Default login timeout of 5 seconds. + // Set default login timeout of 5 seconds. DriverManager.setLoginTimeout(5); } - - /** - * Class constructor. - * Calling this will automatically register this - * manager as the global default. + + /** + * Class constructor. Calling this will automatically register this manager as the global default. */ private DatabaseConditionsManager() { registerConditionsConverter(new DetectorConditionsConverter()); setupConnectionFromSystemProperty(); ConditionsManager.setDefaultConditionsManager(this); setRun(-1); - for (ConditionsObjectConverter converter : converters.values()) { - //logger.fine("registering converter for " + converter.getType()); + for (AbstractConditionsObjectConverter converter : converters.values()) { + // logger.fine("registering converter for " + converter.getType()); registerConditionsConverter(converter); } addConditionsListener(svtSetup); - } - + } + /** * Get the static instance of this class. + * * @return The static instance of the manager. */ - public synchronized static DatabaseConditionsManager getInstance() { + public static synchronized DatabaseConditionsManager getInstance() { logger.finest("getting conditions manager instance"); - + // Is there no manager installed yet? - if (!ConditionsManager.isSetup() || !(ConditionsManager.defaultInstance() instanceof DatabaseConditionsManager)) { + if (!ConditionsManager.isSetup() || + !(ConditionsManager.defaultInstance() instanceof DatabaseConditionsManager)) { logger.finest("creating new DatabaseConditionsManager"); // Create a new instance if necessary, which will install it globally as the default. new DatabaseConditionsManager(); } // Get the instance back from the default conditions system and check that the type is correct now. - ConditionsManager manager = ConditionsManager.defaultInstance(); + final ConditionsManager manager = ConditionsManager.defaultInstance(); if (!(manager instanceof DatabaseConditionsManager)) { logger.severe("default conditions manager has wrong type"); - throw new RuntimeException("Default conditions manager has the wrong type: " + ConditionsManager.defaultInstance().getClass().getName()); - } - + throw new RuntimeException("Default conditions manager has the wrong type: " + + ConditionsManager.defaultInstance().getClass().getName()); + } + logger.finest("returning conditions manager instance"); return (DatabaseConditionsManager) manager; } - + /** * Reset the global static instance of the conditions manager to a new object. */ - public synchronized static void resetInstance() { + public static synchronized void resetInstance() { logger.finest("DatabaseConditionsManager instance is being reset"); new DatabaseConditionsManager(); } - + /** * Set the log level. + * * @param level The log level. */ - public void setLogLevel(Level level) { - logger.config("setting log level to " + level); + public void setLogLevel(final Level level) { + logger.config("setting log level to " + level); logger.setLevel(level); logger.getHandlers()[0].setLevel(level); svtSetup.setLogLevel(level); } - + /** * Open the database connection. + * * @return True if a connection was opened; false if using an existing connection. */ public synchronized boolean openConnection() { @@ -193,25 +283,24 @@ // Setup the default read-only connection, which will choose a SLAC or JLab database. connectionParameters = ConnectionParameters.fromResource(DEFAULT_CONNECTION_PROPERTIES_RESOURCE); } - + if (!loggedConnectionParameters) { // Print out detailed info to the log on first connection within the job. - logger.info("opening connection ... " + '\n' - + "connection: " + connectionParameters.getConnectionString() + '\n' - + "host: " + connectionParameters.getHostname() + '\n' - + "port: " + connectionParameters.getPort() + '\n' - + "user: " + connectionParameters.getUser() + '\n' - + "database: " + connectionParameters.getDatabase()); + logger.info("opening connection ... " + '\n' + "connection: " + + connectionParameters.getConnectionString() + '\n' + "host: " + + connectionParameters.getHostname() + '\n' + "port: " + connectionParameters.getPort() + '\n' + + "user: " + connectionParameters.getUser() + '\n' + "database: " + + connectionParameters.getDatabase()); loggedConnectionParameters = true; } // Create the connection using the parameters. connection = connectionParameters.createConnection(); - isConnected = true; + isConnected = true; openedConnection = true; - } + } logger.info("connection opened successfully"); - + // Flag to indicate whether an existing connection was used or not. return openedConnection; } @@ -225,7 +314,7 @@ try { if (!connection.isClosed()) { connection.close(); - } + } } catch (SQLException e) { throw new RuntimeException(e); } @@ -234,13 +323,14 @@ isConnected = false; logger.info("connection closed"); } - - /** - * Close the database connection but only if there was a connection opened - * based on the flag. Otherwise, it should be left open. + + /** + * Close the database connection but only if there was a connection opened based on the flag. Otherwise, it should + * be left open. + * * @param connectionOpened True to close the connection; false to leave it open. */ - public synchronized void closeConnection(boolean connectionOpened) { + public synchronized void closeConnection(final boolean connectionOpened) { if (connectionOpened) { closeConnection(); } @@ -248,43 +338,47 @@ /** * Get a conditions series with one or more collections. + * * @param collectionType The type of the collection. * @param tableName The name of the data table. + * @param <ObjectType> The type of the conditions object. + * @param <CollectionType> The type of the conditions collection. * @return The conditions series. */ - public + @SuppressWarnings("unchecked") + public <ObjectType extends ConditionsObject, CollectionType extends ConditionsObjectCollection<ObjectType>> - ConditionsSeries<ObjectType, CollectionType> - getConditionsSeries(Class<CollectionType> collectionType, String tableName) { - - TableMetaData metaData = tableRegistry.get(tableName); + ConditionsSeries<ObjectType, CollectionType> getConditionsSeries( + final Class<CollectionType> collectionType, final String tableName) { + + final TableMetaData metaData = tableRegistry.get(tableName); if (metaData == null) { throw new IllegalArgumentException("No table metadata found for type " + collectionType.getName()); } if (!metaData.getCollectionClass().equals(collectionType)) { - throw new IllegalArgumentException("The type " + collectionType.getName() - + " does not match the class " + metaData.getCollectionClass().getName() + " from the meta data"); - } - Class<? extends ConditionsObject> objectType = metaData.getObjectClass(); - ConditionsSeriesConverter<ObjectType, CollectionType> converter = new ConditionsSeriesConverter(objectType, collectionType); + throw new IllegalArgumentException("The type " + collectionType.getName() + " does not match the class " + + metaData.getCollectionClass().getName() + " from the meta data"); + } + final Class<? extends ConditionsObject> objectType = metaData.getObjectClass(); + final ConditionsSeriesConverter<ObjectType, CollectionType> converter = + new ConditionsSeriesConverter(objectType, collectionType); return converter.createSeries(tableName); } - - /** - * This method handles changes to the detector name and run number. - * It is called every time an LCSim event is created, and so it has - * internal logic to figure out if the conditions system actually - * needs to be updated. + + /** + * This method handles changes to the detector name and run number. It is called every time an LCSim event is + * created, and so it has internal logic to figure out if the conditions system actually needs to be updated. */ @Override - public synchronized void setDetector(String detectorName, int runNumber) throws ConditionsNotFoundException { + public synchronized void setDetector(final String detectorName, final int runNumber) + throws ConditionsNotFoundException { logger.finest("setDetector " + detectorName + " with run number " + runNumber); - + if (detectorName == null) { throw new IllegalArgumentException("The detectorName argument is null."); } - + if (!isInitialized || !detectorName.equals(getDetector()) || runNumber != getRun()) { if (!isFrozen) { logger.info("new detector " + detectorName + " and run #" + runNumber); @@ -294,26 +388,29 @@ } } } - + /** * Utility method to determine if a run number is from the 2012 Test Run. + * * @param runNumber The run number. * @return True if run number is from the Test Run. */ - public static boolean isTestRun(int runNumber) { + public static boolean isTestRun(final int runNumber) { return runNumber > 0 && runNumber <= TEST_RUN_MAX_RUN; } - + /** * True if Test Run configuration is selected. + * * @return True if current run is from the Test Run. */ public boolean isTestRun() { return isTestRun; } - + /** * Get the current LCSim compact <code>Detector</code> object. + * * @return The detector object. */ public Detector getDetectorObject() { @@ -322,15 +419,16 @@ /** * Configure this object from an XML file. + * * @param file The XML file. */ - public void setXmlConfig(File fileConfig) { - logger.config("setting XML config from file " + fileConfig.getPath()); - if (!fileConfig.exists()) { - throw new IllegalArgumentException("The config file does not exist: " + fileConfig.getPath()); + public void setXmlConfig(final File file) { + logger.config("setting XML config from file " + file.getPath()); + if (!file.exists()) { + throw new IllegalArgumentException("The config file does not exist: " + file.getPath()); } try { - configure(new FileInputStream(fileConfig)); + configure(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new RuntimeException(e); } @@ -338,50 +436,57 @@ /** * Configure this object from an embedded XML resource. + * * @param resource The embedded XML resource. */ - public void setXmlConfig(String resourceConfig) { - logger.config("setting XML config from resource " + resourceConfig); - InputStream is = getClass().getResourceAsStream(resourceConfig); + public void setXmlConfig(final String resource) { + logger.config("setting XML config from resource " + resource); + final InputStream is = getClass().getResourceAsStream(resource); configure(is); } /** * Set the path to a properties file containing connection settings. + * * @param file The properties file */ - public void setConnectionProperties(File file) { + public void setConnectionProperties(final File file) { logger.config("setting connection properties file " + file.getPath()); - if (!file.exists()) - throw new IllegalArgumentException("The connection properties file does not exist: " + connectionPropertiesFile.getPath()); + if (!file.exists()) { + throw new IllegalArgumentException("The connection properties file does not exist: " + + connectionPropertiesFile.getPath()); + } connectionParameters = ConnectionParameters.fromProperties(file); } - + /** * Set the connection parameters of the conditions database. + * * @param connectionParameters The connection parameters. */ - public void setConnectionParameters(ConnectionParameters connectionParameters) { + public void setConnectionParameters(final ConnectionParameters connectionParameters) { this.connectionParameters = connectionParameters; } /** * Set the connection parameters from an embedded resource location. + * * @param resource The classpath resource location. */ - public void setConnectionResource(String resource) { + public void setConnectionResource(final String resource) { logger.config("setting connection resource " + resource); connectionParameters = ConnectionParameters.fromResource(resource); } /** * Get the next collection ID for a database conditions table. + * * @param tableName The name of the table. * @return The next collection ID. */ - public synchronized int getNextCollectionID(String tableName) { - boolean openedConnection = openConnection(); - ResultSet resultSet = selectQuery("SELECT MAX(collection_id)+1 FROM " + tableName); + public synchronized int getNextCollectionID(final String tableName) { + final boolean openedConnection = openConnection(); + final ResultSet resultSet = selectQuery("SELECT MAX(collection_id)+1 FROM " + tableName); int collectionId = 1; try { resultSet.next(); @@ -396,15 +501,15 @@ } /** - * This method will return true if the given collection ID already exists in - * the table. + * This method will return true if the given collection ID already exists in the table. + * * @param tableName The name of the table. * @param collectionID The collection ID value. * @return True if collection exists. */ - public boolean collectionExists(String tableName, int collectionID) { - String sql = "SELECT * FROM " + tableName + " where collection_id = " + collectionID; - ResultSet resultSet = selectQuery(sql); + public boolean collectionExists(final String tableName, final int collectionID) { + final String sql = "SELECT * FROM " + tableName + " where collection_id = " + collectionID; + final ResultSet resultSet = selectQuery(sql); try { resultSet.last(); } catch (SQLException e) { @@ -416,19 +521,16 @@ } catch (SQLException e) { e.printStackTrace(); } - if (rowCount != 0) { - return true; - } else { - return false; - } - } - + return rowCount != 0; + } + /** * This method can be used to perform a database SELECT query. + * * @param query The SQL query string. * @return The ResultSet from the query or null. */ - ResultSet selectQuery(String query) { + ResultSet selectQuery(final String query) { logger.fine("executing SQL select query ..." + '\n' + query); ResultSet result = null; Statement statement = null; @@ -443,13 +545,14 @@ /** * Perform a SQL query with an update command like INSERT, DELETE or UPDATE. + * * @param query The SQL query string. * @return The keys of the rows affected. */ - public List<Integer> updateQuery(String query) { - boolean openedConnection = openConnection(); + public List<Integer> updateQuery(final String query) { + final boolean openedConnection = openConnection(); logger.fine("executing SQL update query ..." + '\n' + query); - List<Integer> keys = new ArrayList<Integer>(); + final List<Integer> keys = new ArrayList<Integer>(); Statement statement = null; ResultSet resultSet = null; try { @@ -457,93 +560,101 @@ statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); resultSet = statement.getGeneratedKeys(); while (resultSet.next()) { - int key = resultSet.getInt(1); + final int key = resultSet.getInt(1); keys.add(key); } } catch (SQLException x) { throw new RuntimeException("Error in SQL query: " + query, x); - } + } DatabaseUtilities.cleanup(resultSet); - closeConnection(openedConnection); + closeConnection(openedConnection); return keys; } - - /** - * Find a collection of conditions validity records by key name. The key - * name is distinct from the table name, but they are usually set to the - * same value. + + /** + * Find a collection of conditions validity records by key name. The key name is distinct from the table name, but + * they are usually set to the same value. + * * @param name The conditions key name. * @return The set of matching conditions records. */ - public ConditionsRecordCollection findConditionsRecords(String name) { - ConditionsRecordCollection runConditionsRecords = getCachedConditions(ConditionsRecordCollection.class, "conditions").getCachedData(); + public ConditionsRecordCollection findConditionsRecords(final String name) { + final ConditionsRecordCollection runConditionsRecords = getCachedConditions(ConditionsRecordCollection.class, + "conditions").getCachedData(); logger.fine("searching for conditions with name " + name + " in " + runConditionsRecords.size() + " records"); - ConditionsRecordCollection foundConditionsRecords = new ConditionsRecordCollection(); + final ConditionsRecordCollection foundConditionsRecords = new ConditionsRecordCollection(); for (ConditionsRecord record : runConditionsRecords) { if (record.getName().equals(name)) { if (matchesTag(record)) { foundConditionsRecords.add(record); logger.finer("found matching conditions record " + record.getRowId()); } else { - logger.finer("conditions record " + record.getRowId() + " rejected from non-matching tag " + record.getTag()); + logger.finer("conditions record " + record.getRowId() + " rejected from non-matching tag " + + record.getTag()); } } } logger.fine("found " + foundConditionsRecords.size() + " conditions records matching tag " + tag); return foundConditionsRecords; } - + /** * True if there is a conditions record with the given name. + * * @param name The conditions name. * @return True if a conditions record exists with the given name. */ - public boolean hasConditionsRecord(String name) { + public boolean hasConditionsRecord(final String name) { return !findConditionsRecords(name).isEmpty(); } /** * Get a list of all the ConditionsRecord objects. + * * @return The list of all the ConditionsRecord objects. */ // FIXME: This should use a cache that is created during initialization, rather than look these up every time. public ConditionsRecordCollection getConditionsRecords() { logger.finer("getting conditions records ..."); - ConditionsRecordCollection conditionsRecords = new ConditionsRecordCollection(); + final ConditionsRecordCollection conditionsRecords = new ConditionsRecordCollection(); for (TableMetaData tableMetaData : tableRegistry.values()) { try { - ConditionsRecordCollection foundConditionsRecords = findConditionsRecords(tableMetaData.getKey()); - logger.finer("found " + foundConditionsRecords.size() + " collections with name " + tableMetaData.getKey()); - conditionsRecords.addAll(foundConditionsRecords); + final ConditionsRecordCollection foundConditionsRecords = + findConditionsRecords(tableMetaData.getKey()); + logger.finer("found " + foundConditionsRecords.size() + " collections with name " + + tableMetaData.getKey()); + conditionsRecords.addAll(foundConditionsRecords); } catch (Exception e) { e.printStackTrace(); logger.warning(e.getMessage()); } - } + } logger.finer("found " + conditionsRecords + " conditions records"); logger.getHandlers()[0].flush(); return conditionsRecords; } - + /** * Get the combined ECAL conditions for this run. + * * @return The combined ECAL conditions. */ public EcalConditions getEcalConditions() { return this.getCachedConditions(EcalConditions.class, "ecal_conditions").getCachedData(); } - + /** * Get the combined SVT conditions for this run. + * * @return The combined SVT conditions. */ public SvtConditions getSvtConditions() { return this.getCachedConditions(SvtConditions.class, "svt_conditions").getCachedData(); } - - /** - * This method can be called to "freeze" the conditions system so that - * any subsequent updates to run number or detector name will be ignored. + + /** + * This method can be called to "freeze" the conditions system so that any subsequent updates to run number or + * detector name will be ignored. */ public synchronized void freeze() { if (getDetector() != null && getRun() != -1) { @@ -553,7 +664,7 @@ logger.warning("conditions system cannot be frozen because it is not initialized yet"); } } - + /** * Un-freeze the conditions system so that updates will be received again. */ @@ -561,33 +672,38 @@ isFrozen = false; logger.info("conditions system unfrozen"); } - + /** * True if conditions system is frozen. + * * @return True if conditions system is frozen. */ public boolean isFrozen() { return isFrozen; } - + /** * Set a tag used to filter ConditionsRecords. + * * @param tag The tag value used to filter ConditionsRecords. */ - public void setTag(String tag) { + public void setTag(final String tag) { this.tag = tag; logger.info("using conditions tag: " + tag); } /** * Insert a collection of ConditionsObjects into the database. + * * @param collection The collection to insert. + * @param <ObjectType> The type of the conditions object. * @throws SQLException If there is a database error. * @throws ConditionsObjectException If there is a problem with the ConditionsObjects. */ - public <ObjectType extends ConditionsObject> - void insertCollection(ConditionsObjectCollection<ObjectType> collection) throws SQLException, ConditionsObjectException { - + public <ObjectType extends ConditionsObject> void insertCollection( + final ConditionsObjectCollection<ObjectType> collection) + throws SQLException, ConditionsObjectException { + if (collection == null) { throw new IllegalArgumentException("The collection is null."); } @@ -595,42 +711,42 @@ throw new IllegalArgumentException("The collection is empty."); } - TableMetaData tableMetaData = collection.getTableMetaData(); + final TableMetaData tableMetaData = collection.getTableMetaData(); if (tableMetaData == null) { - List<TableMetaData> metaDataList = tableRegistry.findByCollectionType(collection.getClass()); + final List<TableMetaData> metaDataList = tableRegistry.findByCollectionType(collection.getClass()); if (metaDataList == null) { // This is a fatal error because no meta data is available for the type. throw new ConditionsObjectException("Failed to find meta data for type: " + collection.getClass()); - } - logger.fine("using default table meta data " + tableMetaData.getTableName() + " for type " + collection.getClass()); + } } if (collection.getCollectionId() == -1) { try { - collection.setCollectionId(getNextCollectionID(tableMetaData.getTableName())); + collection.setCollectionID(getNextCollectionID(tableMetaData.getTableName())); } catch (ConditionsObjectException e) { throw new RuntimeException(e); } } // FIXME: If collection ID is already set this should be an error! - - logger.info("inserting collection with ID " + collection.getCollectionId() - + " and key " + tableMetaData.getKey() + " into table " + tableMetaData.getTableName()); - - boolean openedConnection = openConnection(); - + + logger.info("inserting collection with ID " + collection.getCollectionId() + " and key " + + tableMetaData.getKey() + " into table " + tableMetaData.getTableName()); + + final boolean openedConnection = openConnection(); + PreparedStatement preparedStatement = null; - + try { connection.setAutoCommit(false); logger.fine("starting insert transaction"); - String sql = QueryBuilder.buildPreparedInsert(tableMetaData.getTableName(), collection.iterator().next()); + final String sql = QueryBuilder.buildPreparedInsert( + tableMetaData.getTableName(), collection.iterator().next()); preparedStatement = connection.prepareStatement(sql); logger.fine("using prepared statement: " + sql); - int collectionId = collection.getCollectionId(); + final int collectionId = collection.getCollectionId(); for (ConditionsObject object : collection) { preparedStatement.setObject(1, collectionId); int parameterIndex = 2; - for (Entry<String,Object> entry : object.getFieldValues().entrySet()) { + for (Entry<String, Object> entry : object.getFieldValues().entrySet()) { preparedStatement.setObject(parameterIndex, entry.getValue()); ++parameterIndex; } @@ -647,82 +763,90 @@ } finally { connection.setAutoCommit(true); } - + try { preparedStatement.close(); } catch (Exception e) { } - + closeConnection(openedConnection); } - + /** * Check if connected to the database. + * * @return true if connected */ public boolean isConnected() { return isConnected; } - - /** - * Get the Logger for this class, which can be used by related sub-classes - * if they do not have their own logger. + + /** + * Get the Logger for this class, which can be used by related sub-classes if they do not have their own logger. + * * @return The Logger for this class. */ public static Logger getLogger() { return logger; } - + /** * Find table information from the name. + * * @param name The name of the table. * @return The table information or null if does not exist. */ - public TableMetaData findTableMetaData(String name) { + public TableMetaData findTableMetaData(final String name) { return tableRegistry.findByTableName(name); } - + /** * Find table information from the collection type. + * * @param type The collection type. * @return The table information or null if does not exist. */ - public List<TableMetaData> findTableMetaData(Class<?> type) { + public List<TableMetaData> findTableMetaData(final Class<?> type) { return tableRegistry.findByCollectionType(type); } - + /** * Get the name of the ECAL in the detector geometry. + * * @return The name of the ECAL. */ public String getEcalName() { return ecalName; } - + /** * Get the subdetector object of the ECAL. + * * @return The ECAL subdetector. */ public Subdetector getEcalSubdetector() { return this.getDetectorObject().getSubdetector(ecalName); } - + /** * True if conditions manager is properly initialized. + * + * @return True if the manager is initialized. */ public boolean isInitialized() { return isInitialized; } - + /** * Get the set of unique conditions tags from the conditions table. + * * @return The list of unique conditions tags. */ public Set<String> getTags() { logger.fine("getting list of available conditions tags"); - boolean openedConnection = openConnection(); - Set<String> tags = new LinkedHashSet<String>(); - ResultSet rs = selectQuery("select distinct(tag) from conditions where tag is not null order by tag"); + final boolean openedConnection = openConnection(); + final Set<String> tags = new LinkedHashSet<String>(); + final ResultSet rs = selectQuery("select distinct(tag) from conditions where tag is not null order by tag"); try { while (rs.next()) { tags.add(rs.getString(1)); @@ -735,32 +859,29 @@ } catch (SQLException e) { logger.log(Level.WARNING, "error closing ResultSet", e); } - StringBuffer buffer = new StringBuffer(); - buffer.append("found unique conditions tags: "); + final StringBuffer sb = new StringBuffer(); + sb.append("found unique conditions tags: "); for (String tag : tags) { - buffer.append(tag + " "); - } - buffer.setLength(buffer.length() - 1); - buffer.append('\n'); - logger.fine(buffer.toString()); + sb.append(tag + " "); + } + sb.setLength(sb.length() - 1); + logger.fine(sb.toString()); closeConnection(openedConnection); return tags; } - /* - ******************************* - * Private methods below here. * - ******************************* - */ - - /** - * Perform all necessary initialization, including setup of the XML - * configuration and loading of conditions onto the Detector. - */ - private void initialize(String detectorName, int runNumber) throws ConditionsNotFoundException { - + /** + * Perform all necessary initialization, including setup of the XML configuration and loading of conditions + * onto the Detector. + * + * @param detectorName The name of the detector model. + * @param runNumber The run number. + * @throws ConditionsNotFoundException If there is a conditions system error. + */ + private void initialize(final String detectorName, final int runNumber) throws ConditionsNotFoundException { + logger.config("initializing with detector " + detectorName + " and run " + runNumber); - + // Is not configured yet? if (!isConfigured) { if (isTestRun(runNumber)) { @@ -778,42 +899,42 @@ // Register the converters for this initialization. logger.fine("registering converters"); registerConverters(); - + // Enable or disable the setup of the SVT detector. logger.fine("enabling SVT setup: " + setupSvtDetector); svtSetup.setEnabled(setupSvtDetector); // Open the database connection. openConnection(); - + // Call the super class's setDetector method to construct the detector object and activate conditions listeners. logger.fine("activating default conditions manager"); super.setDetector(detectorName, runNumber); - + // Should all conditions sets be cached? if (cacheAllConditions) { // Cache the conditions sets of all registered converters. logger.fine("caching all conditions sets ..."); cacheConditionsSets(); } - + if (closeConnectionAfterInitialize) { logger.fine("closing connection after initialization"); - // Close the connection. + // Close the connection. closeConnection(); } - + // Should the conditions system be frozen now? if (freezeAfterInitialize) { // Freeze the conditions system so subsequent updates will be ignored. freeze(); logger.config("system was frozen after initialization"); } - + isInitialized = true; - + logger.info("conditions system initialized successfully"); - + // Flush logger after initialization. logger.getHandlers()[0].flush(); } @@ -826,12 +947,12 @@ // Remove old SVT converter. removeConditionsConverter(svtConverter); } - + if (ecalConverter != null) { // Remove old ECAL converter. registerConditionsConverter(ecalConverter); } - + // Is configured for TestRun? if (isTestRun()) { // Load Test Run specific converters. @@ -847,76 +968,74 @@ registerConditionsConverter(svtConverter); registerConditionsConverter(ecalConverter); } - + /** * Set the name of the ECAL sub-detector. + * * @param ecalName The name of the ECAL. */ - private void setEcalName(String ecalName) { + private void setEcalName(final String ecalName) { if (ecalName == null) { throw new IllegalArgumentException("The ecalName is null"); } this.ecalName = ecalName; logger.info("ECAL name set to " + ecalName); } - + /** * Set the name of the SVT sub-detector. + * * @param svtName The name of the SVT. */ - private void setSvtName(String svtName) { + private void setSvtName(final String svtName) { if (svtName == null) { throw new IllegalArgumentException("The svtName is null"); } this.svtName = svtName; logger.info("SVT name set to " + ecalName); } - + /** * True if the conditions record matches the current tag. + * * @param record The conditions record. * @return True if conditions record matches the currently used tag. */ - private boolean matchesTag(ConditionsRecord record) { + private boolean matchesTag(final ConditionsRecord record) { if (this.tag == null) { // If there is no tag set then all records pass. return true; } - String recordTag = record.getTag(); + final String recordTag = record.getTag(); if (recordTag == null) { // If there is a tag set but the record has no tag, it is rejected. return false; } - if (tag.equals(recordTag)) { - // If the tags match, the record is accepted. - return true; - } else { - // Tags do not match so record is rejected. - return false; - } - } - + return tag.equals(recordTag); + } + /** * Cache conditions sets for all known tables. */ private void cacheConditionsSets() { for (TableMetaData meta : tableRegistry.values()) { try { - logger.fine("caching conditions " + meta.key + " with type "+ meta.collectionClass.getCanonicalName()); + logger.fine("caching conditions " + meta.key + " with type " + meta.collectionClass.getCanonicalName()); getCachedConditions(meta.collectionClass, meta.key); } catch (Exception e) { logger.warning("could not cache conditions " + meta.key); } } - } - + } + /** * Configure this class from an <code>InputStream</code> which should point to an XML document. + * * @param in the InputStream which should be in XML format */ - private void configure(InputStream in) { + private void configure(final InputStream in) { if (!isConfigured) { - SAXBuilder builder = new SAXBuilder(); + final SAXBuilder builder = new SAXBuilder(); Document config = null; try { config = builder.build(in); @@ -934,83 +1053,86 @@ logger.warning("System is already configured, so call to configure is ignored!"); } } - - /** - * Setup the database connection from a file specified by a Java system - * property setting. This could be overridden by subsequent API calls to - * {@link #setConnectionProperties(File)} or {@link #setConnectionResource(String)}. + + /** + * Setup the database connection from a file specified by a Java system property setting. This could be overridden + * by subsequent API calls to {@link #setConnectionProperties(File)} or {@link #setConnectionResource(String)}. */ private void setupConnectionFromSystemProperty() { - String systemPropertiesConnectionPath = (String) System.getProperties().get(CONNECTION_PROPERTY); + final String systemPropertiesConnectionPath = (String) System.getProperties().get(CONNECTION_PROPERTY); if (systemPropertiesConnectionPath != null) { - File f = new File(systemPropertiesConnectionPath); + final File f = new File(systemPropertiesConnectionPath); if (!f.exists()) { - throw new RuntimeException("Connection properties file from " + CONNECTION_PROPERTY + " does not exist."); + throw new RuntimeException("Connection properties file from " + CONNECTION_PROPERTY + + " does not exist."); } setConnectionProperties(f); - logger.info("connection setup from system property " + CONNECTION_PROPERTY + " = " + systemPropertiesConnectionPath); - } + logger.info("connection setup from system property " + CONNECTION_PROPERTY + " = " + + systemPropertiesConnectionPath); + } } /** * Load configuration information from an XML document. + * * @param document The XML document. */ - private void loadConfiguration(Document document) { - - Element node = document.getRootElement().getChild("configuration"); - - if (node == null) + private void loadConfiguration(final Document document) { + + final Element node = document.getRootElement().getChild("configuration"); + + if (node == null) { return; - + } + Element element = node.getChild("setupSvtDetector"); if (element != null) { setupSvtDetector = Boolean.parseBoolean(element.getText()); logger.config("setupSvtDetector = " + setupSvtDetector); } - + element = node.getChild("ecalName"); if (element != null) { setEcalName(element.getText()); } - + element = node.getChild("svtName"); if (element != null) { setSvtName(element.getText()); } - + element = node.getChild("freezeAfterInitialize"); if (element != null) { freezeAfterInitialize = Boolean.parseBoolean(element.getText()); logger.config("freezeAfterInitialize = " + freezeAfterInitialize); } - + element = node.getChild("cacheAllCondition"); if (element != null) { cacheAllConditions = Boolean.parseBoolean(element.getText()); logger.config("cacheAllConditions = " + cacheAllConditions); } - + element = node.getChild("isTestRun"); if (element != null) { isTestRun = Boolean.parseBoolean(element.getText()); logger.config("isTestRun = " + isTestRun); } - + element = node.getChild("logLevel"); if (element != null) { setLogLevel(Level.parse(element.getText())); } - + element = node.getChild("closeConnectionAfterInitialize"); if (element != null) { closeConnectionAfterInitialize = Boolean.parseBoolean(element.getText()); logger.config("closeConnectionAfterInitialize = " + closeConnectionAfterInitialize); } - + element = node.getChild("loginTimeout"); if (element != null) { - Integer timeout = Integer.parseInt(element.getText()); + final Integer timeout = Integer.parseInt(element.getText()); DriverManager.setLoginTimeout(timeout); logger.config("loginTimeout = " + timeout); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseUtilities.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseUtilities.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/DatabaseUtilities.java Thu Apr 2 18:14:47 2015 @@ -5,19 +5,24 @@ /** * Database utility methods. - * @author Jeremy McCormick <[log in to unmask]> * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ +// TODO: Merge this single method into the manager class or a connection utilities class. public final class DatabaseUtilities { - - private DatabaseUtilities() { + + /** + * Do not allow instantiation. + */ + private DatabaseUtilities() { } - + /** * Cleanup a JDBC <code>ResultSet</code> by closing it and its <code>Statement</code> + * * @param resultSet The database ResultSet. */ - static void cleanup(ResultSet resultSet) { + static void cleanup(final ResultSet resultSet) { Statement statement = null; try { statement = resultSet.getStatement(); @@ -28,13 +33,15 @@ resultSet.close(); } } catch (Exception e) { + e.printStackTrace(); } try { if (statement != null) { statement.close(); - } + } } catch (Exception e) { - } + e.printStackTrace(); + } } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/Field.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/Field.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/Field.java Thu Apr 2 18:14:47 2015 @@ -6,16 +6,17 @@ import java.lang.annotation.Target; /** - * This is a java <code>Annotation</code> for assigning a "get" method + * This is a java <code>Annotation</code> for assigning a "get" method * to one or more database table columns. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Field { - + /** * The names of the table columns associated with this method. + * * @return The names of the table column associated with this method. */ String[] names() default ""; -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/MultipleCollectionsAction.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/MultipleCollectionsAction.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/MultipleCollectionsAction.java Thu Apr 2 18:14:47 2015 @@ -1,13 +1,27 @@ package org.hps.conditions.database; /** - * This is the action that should be taken if there are multiple conditions sets - * returned from a query on type and name. - * @author Jeremy McCormick <[log in to unmask]> + * This is the action that should be used to pick a conditions set + * if there are multiple conditions sets returned from a query on + * type and name. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public enum MultipleCollectionsAction { + /** + * Use the updated date. + */ LAST_UPDATED, + /** + * Use the creation date. + */ LAST_CREATED, + /** + * Use the largest run start number. + */ LATEST_RUN_START, + /** + * Throw an error. + */ ERROR } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/QueryBuilder.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/QueryBuilder.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/QueryBuilder.java Thu Apr 2 18:14:47 2015 @@ -9,16 +9,27 @@ /** * This is a static utility class for building SQL queries for the conditions system. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -// TODO: Most methods should be converted to use prepared statements, which is more flexible. public final class QueryBuilder { + /** + * Dot not allow instantiation. + */ private QueryBuilder() { } - - static String buildSelect(String tableName, int collectionId, String[] fields, String order) { + + /** + * Build a SQL select query string. + * @param tableName The name of the table. + * @param collectionId The collection ID. + * @param fields The list of fields. + * @param orderBy The field to order by. + * @return The SQL query string. + */ + static String buildSelect(final String tableName, final int collectionId, final String[] fields, + final String orderBy) { StringBuffer buff = new StringBuffer(); buff.append("SELECT "); if (fields == null) { @@ -32,10 +43,11 @@ buff.delete(buff.length() - 2, buff.length() - 1); } buff.append(" FROM " + tableName); - if (collectionId != -1) + if (collectionId != -1) { buff.append(" WHERE collection_id = " + collectionId); - if (order != null) { - buff.append(" ORDER BY " + order); + } + if (orderBy != null) { + buff.append(" ORDER BY " + orderBy); } return buff.toString(); } @@ -70,14 +82,20 @@ return buff.toString(); } */ - - static String buildPreparedInsert(String tableName, ConditionsObject object) { + + /** + * Build a prepared insert statement for a conditions object. + * @param tableName The name of the table. + * @param object The conditions object. + * @return The prepared insert statement. + */ + static String buildPreparedInsert(final String tableName, final ConditionsObject object) { if (object.getFieldValues().size() == 0) { throw new IllegalArgumentException("The ConditionsObject has no values set."); } - StringBuffer buffer = new StringBuffer(); + final StringBuffer buffer = new StringBuffer(); buffer.append("INSERT INTO " + tableName + "( collection_id, "); - for (String fieldName : object.getFieldValues().keySet()) { + for (String fieldName : object.getFieldValues().keySet()) { buffer.append(" " + fieldName + ","); } buffer.setLength(buffer.length() - 1); @@ -90,34 +108,52 @@ return buffer.toString(); } - static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); - - public static String buildInsert(String tableName, FieldValueMap fieldValues) { + /** + * Date formatting for insert statement. + */ + final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss"); + + /** + * Build an insert statement. + * @param tableName The table name. + * @param fieldValues The field values. + * @return The insert statement. + */ + public static String buildInsert(final String tableName, final FieldValueMap fieldValues) { if (fieldValues.size() == 0) { throw new IllegalArgumentException("The FieldValueMap has no values."); } - StringBuffer buff = new StringBuffer(); - buff.append("INSERT INTO " + tableName + " ("); + final StringBuffer sb = new StringBuffer(); + sb.append("INSERT INTO " + tableName + " ("); for (String fieldName : fieldValues.keySet()) { - buff.append(" " + fieldName + ","); + sb.append(" " + fieldName + ","); } - buff.setLength(buff.length() - 1); - buff.append(" ) VALUES ("); + sb.setLength(sb.length() - 1); + sb.append(" ) VALUES ("); for (Object value : fieldValues.values()) { - String insertValue = value.toString(); + final String insertValue = value.toString(); if (value instanceof Date) { - buff.append(" STR_TO_DATE( '" + dateFormat.format((Date) value) + "', '%Y-%m-%d %H:%i:%S' ),"); + sb.append(" STR_TO_DATE( '" + DATE_FORMAT.format((Date) value) + "', '%Y-%m-%d %H:%i:%S' ),"); } else { - buff.append(" '" + insertValue + "',"); + sb.append(" '" + insertValue + "',"); } } - buff.setLength(buff.length() - 1); - buff.append(")"); - return buff.toString(); + sb.setLength(sb.length() - 1); + sb.append(")"); + return sb.toString(); } - public static String buildInsert(String tableName, int collectionID, List<String> columnNames, List<List<String>> rows) { - StringBuffer buff = new StringBuffer(); + /** + * Build a SQL insert statement. + * @param tableName The table name. + * @param collectionID The collection ID. + * @param columnNames The column names. + * @param rows The row data. + * @return The SQL insert statement. + */ + public static String buildInsert(final String tableName, final int collectionID, + final List<String> columnNames, final List<List<String>> rows) { + final StringBuffer buff = new StringBuffer(); buff.append("INSERT INTO " + tableName + " ( collection_id"); for (String column : columnNames) { buff.append(", " + column); @@ -143,8 +179,13 @@ return query; } */ - - static String formatDate(Date date) { - return dateFormat.format(date); + + /** + * Format the date for insert statement. + * @param date The input date. + * @return The formatted date string. + */ + static String formatDate(final Date date) { + return DATE_FORMAT.format(date); } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/Table.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/Table.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/Table.java Thu Apr 2 18:14:47 2015 @@ -8,16 +8,16 @@ /** * This annotation can be used to assign a class to one * or more database tables. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Table { - + /** * Get the names of the tables. * @return The names of the tables. */ - public String[] names() default ""; + String[] names() default ""; } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/TableMetaData.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/TableMetaData.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/TableMetaData.java Thu Apr 2 18:14:47 2015 @@ -7,7 +7,7 @@ import java.util.Map; import java.util.Set; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.api.ConditionsObject; import org.hps.conditions.api.ConditionsObjectCollection; @@ -19,51 +19,59 @@ * <p> * It also has references to the implementation classes which are used for the ORM * onto {@link ConditionsObject} and {@link ConditionsObjectCollection}. - * + * * @see org.hps.conditions.api.ConditionsObject - * @see org.hps.conditions.api.AbstractConditionsObjectCollection - * - * @author Jeremy McCormick <[log in to unmask]> - * + * @see org.hps.conditions.api.BaseConditionsObjectCollection + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public final class TableMetaData { + /** + * The table name. + */ protected String tableName; + + /** + * The conditions key named (unused???). + */ protected String key; + + /** + * The object class. + */ protected Class<? extends ConditionsObject> objectClass; - protected Class<? extends AbstractConditionsObjectCollection<?>> collectionClass; + + /** + * The collection class. + */ + protected Class<? extends BaseConditionsObjectCollection<?>> collectionClass; + + /** + * The set of field names. + */ protected Set<String> fieldNames = new LinkedHashSet<String>(); + + /** + * The map of field names to their types. + */ protected Map<String, Class<?>> fieldTypes; /** - * The fully qualified constructor. - * @param tableName The name of the table in the conditions database. - * @param objectClass The type of object for the data mapping. - * @param collectionClass The type of collection for the data mapping. + * Fully qualified constructor. + * @param key The conditions key. + * @param tableName The table name. + * @param objectClass The object class. + * @param collectionClass The collection class. + * @param fieldNames The field names. + * @param fieldTypes The field types. */ - /* public TableMetaData( - String key, - String tableName, - Class<? extends ConditionsObject> objectClass, - Class<? extends AbstractConditionsObjectCollection<?>> collectionClass, - Map<String, Class<?>> fieldTypes) { - - this.key = key; - this.tableName = tableName; - this.objectClass = objectClass; - this.collectionClass = collectionClass; - this.fieldTypes = fieldTypes; - } - */ - - public TableMetaData( - String key, - String tableName, - Class<? extends ConditionsObject> objectClass, - Class<? extends AbstractConditionsObjectCollection<?>> collectionClass, - Set<String> fieldNames, - Map<String, Class<?>> fieldTypes) { + final String key, + final String tableName, + final Class<? extends ConditionsObject> objectClass, + final Class<? extends BaseConditionsObjectCollection<?>> collectionClass, + final Set<String> fieldNames, + final Map<String, Class<?>> fieldTypes) { if (key == null) { throw new IllegalArgumentException("key is null"); } @@ -89,7 +97,7 @@ this.fieldNames = fieldNames; this.fieldTypes = fieldTypes; } - + /** * Get the type of object this table maps onto. * @return The type of object. @@ -100,9 +108,9 @@ /** * Get the type of collection this table maps onto. - * @return + * @return The collection class. */ - public Class<? extends AbstractConditionsObjectCollection<?>> getCollectionClass() { + public Class<? extends BaseConditionsObjectCollection<?>> getCollectionClass() { return collectionClass; } @@ -118,7 +126,7 @@ * Get the type of the field called <code>fieldName</code>. * @return The type of the field. */ - public Class<?> getFieldType(String fieldName) { + public Class<?> getFieldType(final String fieldName) { return fieldTypes.get(fieldName); } @@ -129,7 +137,7 @@ public String getTableName() { return tableName; } - + /** * Get the key of this conditions type. May be different from table name but * is usually the same. @@ -138,8 +146,14 @@ public String getKey() { return key; } - - static public List<TableMetaData> findByObjectType(List<TableMetaData> tableMetaDataList, Class<? extends ConditionsObject> objectType) { + + /** + * Find table meta data by object type. + * @param tableMetaDataList The list of table meta data e.g. from the registry. + * @param objectType The type of the object. + * @return The list of table meta data that have that object type. + */ + public static List<TableMetaData> findByObjectType(List<TableMetaData> tableMetaDataList, Class<? extends ConditionsObject> objectType) { List<TableMetaData> list = new ArrayList<TableMetaData>(); for (TableMetaData tableMetaData : tableMetaDataList) { if (tableMetaData.getObjectClass().equals(objectType)) { @@ -150,6 +164,10 @@ return list; } + /** + * Convert to a string. + * @return This object converted to a string. + */ public String toString() { StringBuffer buff = new StringBuffer(); buff.append("tableMetaData: tableName = " + this.getTableName()); Modified: java/trunk/conditions/src/main/java/org/hps/conditions/database/TableRegistry.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/TableRegistry.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/TableRegistry.java Thu Apr 2 18:14:47 2015 @@ -8,17 +8,25 @@ import java.util.Map; import java.util.Set; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.api.ConditionsObject; import org.hps.conditions.api.ConditionsObjectUtilities; /** * This is a registry providing a map between tables and their meta-data. - * @author Jeremy McCormick <[log in to unmask]> + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public final class TableRegistry extends HashMap<String, TableMetaData> { - + + /** + * Maps types to table meta data. + */ static class ObjectTypeMap extends HashMap<Class<? extends ConditionsObject>, List<TableMetaData>> { + /** + * Add a connection between an object type and table meta data. + * @param type The object type. + * @param metaData The table meta data. + */ void add(Class<? extends ConditionsObject> type, TableMetaData metaData) { if (this.get(type) == null) { this.put(type, new ArrayList<TableMetaData>()); @@ -26,39 +34,63 @@ this.get(type).add(metaData); } } - - static class CollectionTypeMap extends HashMap<Class<? extends AbstractConditionsObjectCollection<?>>, List<TableMetaData>> { - void add(Class<? extends AbstractConditionsObjectCollection<?>> type, TableMetaData metaData) { + + /** + * Maps collection types to table meta data. + */ + static class CollectionTypeMap extends HashMap<Class<? extends BaseConditionsObjectCollection<?>>, List<TableMetaData>> { + /** + * Add a connection between a collection type and table meta data. + * @param type The collection type. + * @param metaData The table meta data. + */ + void add(Class<? extends BaseConditionsObjectCollection<?>> type, TableMetaData metaData) { if (this.get(type) == null) { this.put(type, new ArrayList<TableMetaData>()); } this.get(type).add(metaData); - } + } } + + /** + * Map between object types and meta data. + */ + private ObjectTypeMap objectTypeMap = new ObjectTypeMap(); - ObjectTypeMap objectTypeMap = new ObjectTypeMap(); - CollectionTypeMap collectionTypeMap = new CollectionTypeMap(); - + /** + * Map between collection types and meta data. + */ + private CollectionTypeMap collectionTypeMap = new CollectionTypeMap(); + + /** + * Class should not be directly instantiated. + * <p> + * Use the {@link #create()} method instead. + */ private TableRegistry() { } - + + /** + * Create a new table meta data registry. + * @return The meta data registry. + */ static TableRegistry create() { TableRegistry registry = new TableRegistry(); for (Class<? extends ConditionsObject> objectType : ConditionsObjectUtilities.findConditionsObjectTypes()) { - + // Get the collection type. - Class<? extends AbstractConditionsObjectCollection<?>> collectionType = + Class<? extends BaseConditionsObjectCollection<?>> collectionType = ConditionsObjectUtilities.getCollectionType(objectType); - + // Get the list of field names. - Set<String> fieldNames = ConditionsObjectUtilities.getFieldNames(objectType); - + Set<String> fieldNames = ConditionsObjectUtilities.getFieldNames(objectType); + // Create map of fields to their types. Map<String, Class<?>> fieldTypes = new HashMap<String, Class<?>>(); for (Method method : objectType.getMethods()) { if (!method.getReturnType().equals(Void.TYPE)) { for (Annotation annotation : method.getAnnotations()) { - if (annotation.annotationType().equals(Field.class)) { + if (annotation.annotationType().equals(Field.class)) { Field field = (Field) annotation; for (String fieldName : field.names()) { fieldTypes.put(fieldName, method.getReturnType()); @@ -67,30 +99,49 @@ } } } - - for (String name : ConditionsObjectUtilities.getTableNames(objectType)) { + + for (String name : ConditionsObjectUtilities.getTableNames(objectType)) { // Create a meta data mapping for each table name in the class description. TableMetaData data = new TableMetaData(name, name, objectType, collectionType, fieldNames, fieldTypes); - registry.put(name, data); + registry.put(name, data); registry.objectTypeMap.add(objectType, data); - registry.collectionTypeMap.add(collectionType, data); + registry.collectionTypeMap.add(collectionType, data); } } return registry; } - + + /** + * Find meta data by object type. + * @param objectType The object type. + * @return The meta data or null if none exists. + */ List<TableMetaData> findByObjectType(Class<? extends ConditionsObject> objectType) { return objectTypeMap.get(objectType); } - + + /** + * Find meta data by collection type. + * @param collectionType The collection type. + * @return The meta data or null if none exists. + */ List<TableMetaData> findByCollectionType(Class<?> collectionType) { return collectionTypeMap.get(collectionType); } - + + /** + * Find meta data by table name. + * @param name The table name. + * @return The meta data or null if none exists. + */ TableMetaData findByTableName(String name) { return this.get(name); } - + + /** + * Convert this object to a string. + * @return This object converted to a string. + */ public String toString() { StringBuffer buff = new StringBuffer(); for (TableMetaData tableMetaData : this.values()) { Added: java/trunk/conditions/src/main/java/org/hps/conditions/database/package-info.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/database/package-info.java (added) +++ java/trunk/conditions/src/main/java/org/hps/conditions/database/package-info.java Thu Apr 2 18:14:47 2015 @@ -0,0 +1,12 @@ +/** + * This package contains classes for converting database information + * into conditions classes as well as updating the records from the + * objects. + * + * @see DatabaseConditionsManager + * @see TableMetaData + * @see AbstractConditionsObjectConverter + * @see ConditionsSeriesConverter + * @author Jeremy McCormick <[log in to unmask]> + */ +package org.hps.conditions.database; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalBadChannel.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalBadChannel.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalBadChannel.java Thu Apr 2 18:14:47 2015 @@ -2,8 +2,8 @@ import java.util.Comparator; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -15,15 +15,32 @@ */ @Table(names = {"ecal_bad_channels", "test_run_ecal_bad_channels"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_UPDATED) -public final class EcalBadChannel extends AbstractConditionsObject { +public final class EcalBadChannel extends BaseConditionsObject { - public static class EcalBadChannelCollection extends AbstractConditionsObjectCollection<EcalBadChannel> { + /** + * The collection class for this object. + */ + @SuppressWarnings("serial") + public static class EcalBadChannelCollection extends BaseConditionsObjectCollection<EcalBadChannel> { - public AbstractConditionsObjectCollection<EcalBadChannel> sorted() { + /** + * Sort and return the collection without modifying in place. + * @return The sorted collection. + */ + public BaseConditionsObjectCollection<EcalBadChannel> sorted() { return sorted(new ChannelIdComparator()); } + /** + * Comparison class for ECAL bad channels, which uses channel ID. + */ class ChannelIdComparator implements Comparator<EcalBadChannel> { + /** + * Compare two ECAL bad channel objects. + * @param o1 The first object. + * @param o2 The second object. + * @return -1, 0, 1 if first channel ID is less than, equal to, or greater than the second. + */ public int compare(EcalBadChannel o1, EcalBadChannel o2) { if (o1.getChannelId() < o2.getChannelId()) { return -1; @@ -33,15 +50,15 @@ return 0; } } - } + } } - + /** * Get the ECAL channel ID. * @return The ECAL channel ID. */ @Field(names = {"ecal_channel_id"}) public int getChannelId() { - return getFieldValue("ecal_channel_id"); + return getFieldValue("ecal_channel_id"); } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCalibration.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCalibration.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCalibration.java Thu Apr 2 18:14:47 2015 @@ -2,8 +2,8 @@ import java.util.Comparator; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -12,24 +12,41 @@ /** * This class is a simplistic representation of ECal pedestal and noise values * from the conditions database. - * + * * The pedestal and noise are in units of ADC counts. They are the mean and the * standard deviation of the digitized pre-amp output. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Table(names = {"ecal_calibrations", "test_run_ecal_calibrations", "ecal_hardware_calibrations"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class EcalCalibration extends AbstractConditionsObject { +public final class EcalCalibration extends BaseConditionsObject { - public static class EcalCalibrationCollection extends AbstractConditionsObjectCollection<EcalCalibration> { - - public AbstractConditionsObjectCollection<EcalCalibration> sorted() { + /** + * The collection implementation for the object class. + */ + @SuppressWarnings("serial") + public static class EcalCalibrationCollection extends BaseConditionsObjectCollection<EcalCalibration> { + + /** + * Sort and return the collection but do no modify in place. + * @return The sorted collection. + */ + public BaseConditionsObjectCollection<EcalCalibration> sorted() { return sorted(new ChannelIdComparator()); } - + + /** + * Comparison using channel ID. + */ class ChannelIdComparator implements Comparator<EcalCalibration> { - public int compare(EcalCalibration o1, EcalCalibration o2) { + /** + * Compare two ECAL calibration objects. + * @param o1 The first object. + * @param o2 The second object. + * @return -1, 0, 1 if first channel ID is less than, equal to, or greater than the second. + */ + public int compare(final EcalCalibration o1, final EcalCalibration o2) { if (o1.getChannelId() < o2.getChannelId()) { return -1; } else if (o1.getChannelId() > o2.getChannelId()) { @@ -40,11 +57,20 @@ } } } - + + /** + * No argument constructor. + */ public EcalCalibration() { } - - public EcalCalibration(int channelId, double pedestal, double noise) { + + /** + * Full qualified constructor. + * @param channelId The channel ID. + * @param pedestal The pedestal measurement (ADC counts). + * @param noise The noise measured as RMS. + */ + public EcalCalibration(final int channelId, final double pedestal, final double noise) { this.setFieldValue("ecal_channel_id", channelId); this.setFieldValue("pedestal", pedestal); this.setFieldValue("noise", noise); @@ -56,12 +82,12 @@ */ @Field(names = {"ecal_channel_id"}) public int getChannelId() { - return getFieldValue("ecal_channel_id"); + return getFieldValue("ecal_channel_id"); } /** * Get the pedestal value in units of ADC counts, which is the mean of the - * digitized pre-amp output. + * digitized preamplifier output. * @return The gain value. */ @Field(names = {"pedestal"}) @@ -71,7 +97,7 @@ /** * Get the noise value in units of ADC counts, which is the standard - * deviation of the digitized pre-amp output. + * deviation of the digitized preamplifier output. * @return The noise value. */ @Field(names = {"noise"}) Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannel.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannel.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannel.java Thu Apr 2 18:14:47 2015 @@ -4,10 +4,10 @@ import java.util.HashMap; import java.util.Map; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; import org.hps.conditions.api.AbstractIdentifier; -import org.hps.conditions.database.ConditionsObjectConverter; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; +import org.hps.conditions.database.AbstractConditionsObjectConverter; import org.hps.conditions.database.Converter; import org.hps.conditions.database.DatabaseConditionsManager; import org.hps.conditions.database.Field; @@ -22,27 +22,40 @@ /** * This class encapsulates all the information about a single ECal channel, * corresponding to one physical crystal in the detector. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Table(names = {"ecal_channels", "test_run_ecal_channels"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED, converter = EcalChannel.EcalChannelConverter.class) -public final class EcalChannel extends AbstractConditionsObject { - - public static final class EcalChannelConverter extends ConditionsObjectConverter<EcalChannelCollection> { - +public final class EcalChannel extends BaseConditionsObject { + + /** + * Customized converter for this object. + */ + public static final class EcalChannelConverter extends AbstractConditionsObjectConverter<EcalChannelCollection> { + + /** + * Create an {@link EcalChannel} collection. + * @param conditionsManager The conditions manager. + * @param name The name of the conditions data table. + * @return The collection of ECAL channel objects. + */ @Override public EcalChannelCollection getData(ConditionsManager conditionsManager, String name) { - EcalChannelCollection collection = super.getData(conditionsManager, name); - Subdetector ecal = DatabaseConditionsManager.getInstance().getEcalSubdetector(); + final EcalChannelCollection collection = super.getData(conditionsManager, name); + final Subdetector ecal = DatabaseConditionsManager.getInstance().getEcalSubdetector(); collection.buildGeometryMap(ecal.getDetectorElement().getIdentifierHelper(), ecal.getSystemID()); return collection; } + /** + * Get the type this converter handles. + * @return The type this converter handles. + */ @Override public Class<EcalChannelCollection> getType() { return EcalChannelCollection.class; - } + } } /** @@ -51,22 +64,45 @@ */ public static final class DaqId extends AbstractIdentifier { + /** + * The DAQ crate number. + */ private int crate = -1; + + /** + * The DAQ slot number. + */ private int slot = -1; + + /** + * The DAQ channel number. + */ private int channel = -1; - public DaqId(int values[]) { + /** + * Create a DAQ ID from an array of values. + * @param values The list of values (crate, slot, channel). + */ + public DaqId(final int values[]) { crate = values[0]; slot = values[1]; channel = values[2]; } + /** + * Encode this ID into a long value. + * @return The encoded long value. + */ @Override public long encode() { // from Sho's code return (((long) crate) << 32) | ((long) slot << 16) | (long) channel; } + /** + * Check if the values look valid. + * @return True if ID's values are valid. + */ @Override public boolean isValid() { return crate != -1 && slot != -1 && channel != -1; @@ -79,19 +115,42 @@ */ public static final class GeometryId extends AbstractIdentifier { + /** + * The subdetector system ID. + */ private int system = -1; + + /** + * The crystal's X index. + */ private int x = Integer.MAX_VALUE; + + /** + * The crystal's Y index. + */ private int y = Integer.MAX_VALUE; + /** + * The helper for using identifiers. + */ private IIdentifierHelper helper; - public GeometryId(IIdentifierHelper helper, int[] values) { + /** + * Create a geometry ID. + * @param helper The ID helper. + * @param values The list of values (system, x, y). + */ + public GeometryId(final IIdentifierHelper helper, final int[] values) { this.helper = helper; system = values[0]; x = values[1]; y = values[2]; } + /** + * Encode this ID as a long using the ID helper. + * @return The encoded long value. + */ @Override public long encode() { IExpandedIdentifier expId = new ExpandedIdentifier(helper.getIdentifierDictionary().getNumberOfFields()); @@ -101,6 +160,10 @@ return helper.pack(expId).getValue(); } + /** + * True if ID's values look valid. + * @return True if ID is valid. + */ @Override public boolean isValid() { return system != -1 && x != Integer.MAX_VALUE && y != Integer.MAX_VALUE; @@ -117,31 +180,60 @@ */ public static final class ChannelId extends AbstractIdentifier { + /** + * The channel ID value. + */ private int id = -1; + /** + * Create a channel ID. + * @param values The values (size 0 with single int value). + */ public ChannelId(int[] values) { id = values[0]; } + /** + * Encode as long value (just returns the int value). + * @return The ID's value. + */ @Override public long encode() { return id; } + /** + * True if ID looks valid. + * @return True if ID looks valid. + */ @Override public boolean isValid() { return id != -1; } } - + + /** + * Create a {@link DaqId} for this ECAL channel. + * @return The DAQ Id for this ECAL channel. + */ DaqId createDaqId() { return new DaqId(new int[] { getCrate(), getSlot(), getChannel() }); } + /** + * Create a {@link GeometryId} for this ECAL channel. + * @param helper The ID helper. + * @param system The subdetector system ID. + * @return The geometry ID. + */ GeometryId createGeometryId(IIdentifierHelper helper, int system) { return new GeometryId(helper, new int[] { system, getX(), getY() }); } + /** + * Create a channel ID for this ECAL channel. + * @return The channel ID. + */ ChannelId createChannelId() { return new ChannelId(new int[] { this.getChannelId() }); } @@ -149,36 +241,51 @@ /** * A collection of {@link EcalChannel} objects. */ - public static class EcalChannelCollection extends AbstractConditionsObjectCollection<EcalChannel> { - - // Identifier maps for fast lookup. - Map<Long, EcalChannel> daqMap = new HashMap<Long, EcalChannel>(); - Map<Long, EcalChannel> geometryMap = new HashMap<Long, EcalChannel>(); + public static class EcalChannelCollection extends BaseConditionsObjectCollection<EcalChannel> { + + /** + * Map of {@link DaqId} to channel object. + */ + private Map<Long, EcalChannel> daqMap = new HashMap<Long, EcalChannel>(); + + /** + * Map of {@link GeometryId} to channel object. + */ + private Map<Long, EcalChannel> geometryMap = new HashMap<Long, EcalChannel>(); + + /** + * Map of {@link ChannelId} to channel object. + */ Map<Long, EcalChannel> channelMap = new HashMap<Long, EcalChannel>(); /** * Add an <code>EcalChannel</code> to the collection and cache its ID * information. The GeometryId must be created later as it requires * access to the Detector API. - */ - @Override - public boolean add(EcalChannel channel) { + * + * @param channel The ECAL channel object. + * @return True if object was added successfully. + */ + @Override + public boolean add(final EcalChannel channel) { super.add(channel); - DaqId daqId = channel.createDaqId(); - if (daqId.isValid()) + final DaqId daqId = channel.createDaqId(); + if (daqId.isValid()) { daqMap.put(daqId.encode(), channel); - ChannelId channelId = channel.createChannelId(); - if (channelId.isValid()) + } + final ChannelId channelId = channel.createChannelId(); + if (channelId.isValid()) { channelMap.put(channelId.encode(), channel); + } return true; } /** - * Build the map of geometry IDs. + * Build the map of {@link GeometryId} objects. * @param helper The identifier helper of the subdetector. * @param system The system ID of the subdetector. */ - void buildGeometryMap(IIdentifierHelper helper, int system) { + void buildGeometryMap(final IIdentifierHelper helper, final int system) { for (EcalChannel channel : this) { GeometryId geometryId = channel.createGeometryId(helper, system); geometryMap.put(geometryId.encode(), channel); @@ -190,7 +297,7 @@ * @param daqId The DAQ ID object. * @return The matching channel or null if does not exist. */ - public EcalChannel findChannel(DaqId daqId) { + public EcalChannel findChannel(final DaqId daqId) { return daqMap.get(daqId.encode()); } @@ -199,7 +306,7 @@ * @param geometryId The geometric ID object. * @return The matching channel or null if does not exist. */ - public EcalChannel findChannel(GeometryId geometryId) { + public EcalChannel findChannel(final GeometryId geometryId) { return geometryMap.get(geometryId.encode()); } @@ -208,7 +315,7 @@ * @param channelId The channel ID object. * @return The matching channel or null if does not exist. */ - public EcalChannel findChannel(ChannelId channelId) { + public EcalChannel findChannel(final ChannelId channelId) { return channelMap.get(channelId.encode()); } @@ -217,7 +324,7 @@ * @param id The encoded geometric ID. * @return The matching channel or null if does not exist. */ - public EcalChannel findGeometric(long id) { + public EcalChannel findGeometric(final long id) { return geometryMap.get(id); } @@ -226,7 +333,7 @@ * @param id The encoded channel ID. * @return The matching channel or null if does not exist. */ - public EcalChannel findChannel(long id) { + public EcalChannel findChannel(final long id) { return channelMap.get(id); } @@ -235,15 +342,28 @@ * @param id The encoded DAQ ID. * @return The matching channel or null if does not exist. */ - public EcalChannel findDaq(long id) { + public EcalChannel findDaq(final long id) { return daqMap.get(id); } - - public AbstractConditionsObjectCollection<EcalChannel> sorted() { + + /** + * Sort collection and return but do not sort in place. + * @return The sorted copy of the collection. + */ + public BaseConditionsObjectCollection<EcalChannel> sorted() { return sorted(new ChannelIdComparator()); } - - class ChannelIdComparator implements Comparator<EcalChannel> { + + /** + * Comparison of ECAL channel objects. + */ + class ChannelIdComparator implements Comparator<EcalChannel> { + /** + * Compare two ECAL channel objects using their channel ID. + * @param c1 The first object. + * @param c2 The second object. + * @return -1, 0, or 1 if first channel is less than, equal to or greater than second. + */ public int compare(EcalChannel c1, EcalChannel c2) { if (c1.getChannelId() < c2.getChannelId()) { return -1; @@ -252,14 +372,14 @@ } else { return 0; } - } + } } } /** * Get the crate number of the channel. * @return The crate number. - * + * */ @Field(names = {"crate"}) public int getCrate() { @@ -313,9 +433,10 @@ /** * Implementation of equals. + * @param o The object to compare equality to. * @return True if objects are equal. */ - public boolean equals(Object o) { + public boolean equals(final Object o) { if (o == null) { return false; } @@ -325,7 +446,8 @@ if (o == this) { return true; } - EcalChannel c = (EcalChannel) o; - return c.getChannelId() == getChannelId() && c.getCrate() == getCrate() && c.getSlot() == getSlot() && c.getChannel() == getChannel() && c.getX() == getX() && c.getY() == getY(); - } -} + final EcalChannel c = (EcalChannel) o; + return c.getChannelId() == getChannelId() && c.getCrate() == getCrate() && c.getSlot() == getSlot() + && c.getChannel() == getChannel() && c.getX() == getX() && c.getY() == getY(); + } +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannelConstants.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannelConstants.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalChannelConstants.java Thu Apr 2 18:14:47 2015 @@ -2,14 +2,38 @@ /** * This class represents ECAL conditions per channel. - * @author Jeremy McCormick <[log in to unmask]> + * <p> + * It is an aggregation of various ECAL conditions objects + * that are associated to a single channel. + * + * @see EcalGain + * @see EcalCalibration + * @see EcalTimeShift + * @see EcalBadChannel + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public final class EcalChannelConstants { - EcalGain gain = null; - EcalCalibration calibration = null; - EcalTimeShift timeShift = null; - boolean badChannel = false; + /** + * The channel {@link EcalGain} conditions. + */ + private EcalGain gain = null; + + /** + * The channel {@link EcalCalibration} conditions. + */ + private EcalCalibration calibration = null; + + /** + * The channel {@link EcalTimeShift} conditions. + */ + private EcalTimeShift timeShift = null; + + /** + * True if channel is bad and should not be used for reconstruction. + */ + private boolean badChannel = false; /** * Class constructor, which is package protected. @@ -21,7 +45,7 @@ * Set the gain. * @param gain The gain object. */ - void setGain(EcalGain gain) { + void setGain(final EcalGain gain) { this.gain = gain; } @@ -29,7 +53,7 @@ * Set the calibration. * @param calibration The calibration object. */ - void setCalibration(EcalCalibration calibration) { + void setCalibration(final EcalCalibration calibration) { this.calibration = calibration; } @@ -37,7 +61,7 @@ * Set the time shift. * @param timeShift the time shift */ - void setTimeShift(EcalTimeShift timeShift) { + void setTimeShift(final EcalTimeShift timeShift) { this.timeShift = timeShift; } @@ -45,7 +69,7 @@ * Set whether this is a bad channel. * @param badChannel set to true to flag channel as bad */ - void setBadChannel(boolean badChannel) { + void setBadChannel(final boolean badChannel) { this.badChannel = badChannel; } @@ -67,18 +91,17 @@ /** * Get the time shift. - * @return the time shift + * @return The time shift. */ public EcalTimeShift getTimeShift() { return timeShift; } /** - * Get whether this channel is bad or not. - * @return True if channel is bad; false if not. + * True if this is a bad channel. + * @return True if channel is bad. */ public boolean isBadChannel() { return badChannel; } - } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditions.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditions.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditions.java Thu Apr 2 18:14:47 2015 @@ -11,47 +11,57 @@ /** * This class provides access to all ECAL conditions from the database, * including gain, pedestal and bad channel settings, per crystal. - * + * <p> * Unlike most conditions data types, it does not extend * {@link org.hps.conditions.api.ConditionsObject}, because it is a composite object - * containing data assembled from many other - * {@link org.hps.conditions.ConditionsObjects}. - * - * @author Jeremy McCormick <[log in to unmask]> + * containing data assembled from many other {@link org.hps.conditions.ConditionsObjects} + * and has a special data converter {@link EcalConditionsConverter}. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public final class EcalConditions { - // Channel collection. - EcalChannelCollection channelCollection = new EcalChannelCollection(); + /** + * The collection of {@link EcalChannel} objects. + */ + private EcalChannelCollection channelCollection = new EcalChannelCollection(); - // Map between channels and their conditions data. - Map<EcalChannel, EcalChannelConstants> channelConstants = new HashMap<EcalChannel, EcalChannelConstants>(); + /** + * Map between channels and their conditions constants. + */ + private final Map<EcalChannel, EcalChannelConstants> channelConstants = + new HashMap<EcalChannel, EcalChannelConstants>(); - // Map between geometry stations and channel. - EcalCrystalChannelMap crystalMap; - - // Reference to the current ECAL subdetector in the geometry. - Subdetector subdetector; - /** - * Class constructor, which is package protected. + * Map between channels and geometric crystals. */ - EcalConditions(Subdetector subdetector) { + private EcalCrystalChannelMap crystalMap; + + /** + * The current ECAL subdetector in the geometry. + */ + private final Subdetector subdetector; + + /** + * Class constructor. + * @param subdetector The ECAL subdetector object. + */ + EcalConditions(final Subdetector subdetector) { if (subdetector == null) { throw new IllegalArgumentException("The subdetector argument is null."); } - this.subdetector = subdetector; + this.subdetector = subdetector; } /** * Set the channel map. - * @param channels The channel map. + * @param channelCollection The channel map. */ - void setChannelCollection(EcalChannelCollection channelCollection) { + void setChannelCollection(final EcalChannelCollection channelCollection) { this.channelCollection = channelCollection; - + // Build the map between crystals and channels. - crystalMap = new EcalCrystalChannelMap((HPSEcalAPI)subdetector.getDetectorElement(), channelCollection); + crystalMap = new EcalCrystalChannelMap((HPSEcalAPI) subdetector.getDetectorElement(), channelCollection); } /** @@ -61,99 +71,106 @@ public EcalChannelCollection getChannelCollection() { return channelCollection; } - + /** * Get the channel information for a geometric crystal. * @param crystal The geometric crystal. * @return The channel information or null if does not exist. */ - public EcalChannel getChannel(EcalCrystal crystal) { + public EcalChannel getChannel(final EcalCrystal crystal) { return crystalMap.getEcalChannel(crystal); } - + /** * Get the conditions constants for a specific channel. These will be * created if they do not exist for the given channel, BUT only channels in * the channel map are accepted as an argument. * @param channel The ECAL channel. * @return The conditions constants for the channel. - * @throws IllegalArgumentException if channel does not exist in the channel - * map. + * @throws IllegalArgumentException if channel does not exist in the channel map. */ - public EcalChannelConstants getChannelConstants(EcalChannel channel) { + public EcalChannelConstants getChannelConstants(final EcalChannel channel) { // This channel must come from the map. if (!channelCollection.contains(channel)) { System.err.println("Channel not found in map: " + channel); throw new IllegalArgumentException("Channel was not found in map."); } // If channel has no data yet, then add it. - if (!channelConstants.containsKey(channel)) + if (!channelConstants.containsKey(channel)) { channelConstants.put(channel, new EcalChannelConstants()); + } return channelConstants.get(channel); } /** + * This is just used for a divider length in print output. + */ + private static final int DIVIDER_SIZE = 91; + + /** * Convert this object to a string. * @return A string representation of this object. */ + // FIXME: The print out from this method looks like a mess. public String toString() { - StringBuffer buff = new StringBuffer(); + final StringBuffer sb = new StringBuffer(); - buff.append('\n'); - buff.append("Printing ECAL conditions ..."); - buff.append('\n'); - buff.append('\n'); + sb.append('\n'); + sb.append("Printing ECAL conditions ..."); + sb.append('\n'); + sb.append('\n'); // Table header: - buff.append("id"); - buff.append(" "); - buff.append("crate"); - buff.append(" "); - buff.append("slot"); - buff.append(" "); - buff.append("channel"); - buff.append(" "); - buff.append("x"); - buff.append(" "); - buff.append("y"); - buff.append(" "); - buff.append("gain"); - buff.append(" "); - buff.append("pedestal"); - buff.append(" "); - buff.append("noise"); - buff.append(" "); - buff.append("time_shift"); - buff.append(" "); - buff.append("bad"); - buff.append('\n'); - for (int i = 0; i < 91; i++) { - buff.append("-"); + sb.append("id"); + sb.append(" "); + sb.append("crate"); + sb.append(" "); + sb.append("slot"); + sb.append(" "); + sb.append("channel"); + sb.append(" "); + sb.append("x"); + sb.append(" "); + sb.append("y"); + sb.append(" "); + sb.append("gain"); + sb.append(" "); + sb.append("pedestal"); + sb.append(" "); + sb.append("noise"); + sb.append(" "); + sb.append("time_shift"); + sb.append(" "); + sb.append("bad"); + sb.append('\n'); + for (int i = 0; i < DIVIDER_SIZE; i++) { + sb.append("-"); } - buff.append('\n'); + sb.append('\n'); // Loop over all channels. for (EcalChannel channel : channelCollection) { - EcalChannelConstants constants = getChannelConstants(channel); + final EcalChannelConstants constants = getChannelConstants(channel); - double gain = constants.getGain().getGain(); - double pedestal = constants.getCalibration().getPedestal(); - double noise = constants.getCalibration().getNoise(); - double timeShift = constants.getTimeShift().getTimeShift(); - boolean bad = constants.isBadChannel(); + final double gain = constants.getGain().getGain(); + final double pedestal = constants.getCalibration().getPedestal(); + final double noise = constants.getCalibration().getNoise(); + final double timeShift = constants.getTimeShift().getTimeShift(); + final boolean bad = constants.isBadChannel(); // Channel data. - buff.append(String.format("%-5d %-6d %-6d %-8d %-6d %-6d", channel.getChannelId(), channel.getCrate(), channel.getSlot(), channel.getChannel(), channel.getX(), channel.getY())); + sb.append(String.format("%-5d %-6d %-6d %-8d %-6d %-6d", channel.getChannelId(), channel.getCrate(), + channel.getSlot(), channel.getChannel(), channel.getX(), channel.getY())); // Constants. - buff.append(String.format("%-10.4f %-10.4f %-10.4f %-11.4f", gain, pedestal, noise, timeShift)); + sb.append(String.format("%-10.4f %-10.4f %-10.4f %-11.4f", gain, pedestal, noise, timeShift)); // Bad channel. - buff.append(bad); + sb.append(bad); - buff.append('\n'); + sb.append('\n'); } - return buff.toString(); + return sb.toString(); } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsConverter.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsConverter.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsConverter.java Thu Apr 2 18:14:47 2015 @@ -1,6 +1,4 @@ package org.hps.conditions.ecal; - -import java.util.logging.Logger; import org.hps.conditions.api.ConditionsObjectCollection; import org.hps.conditions.api.ConditionsSeries; @@ -11,89 +9,118 @@ import org.hps.conditions.ecal.EcalChannel.EcalChannelCollection; import org.hps.conditions.ecal.EcalGain.EcalGainCollection; import org.hps.conditions.ecal.EcalTimeShift.EcalTimeShiftCollection; -import org.hps.conditions.svt.AbstractSvtConditionsConverter; import org.lcsim.conditions.ConditionsConverter; import org.lcsim.conditions.ConditionsManager; import org.lcsim.geometry.Detector; -import org.lcsim.util.log.LogUtil; /** - * This class loads all ECal conditions into an {@link EcalConditions} object + * This class loads all ECAL conditions into an {@link EcalConditions} object * from the database, based on the current run number known by the conditions * manager. - * - * @author Jeremy McCormick <[log in to unmask]> - * @author Omar Moreno <[log in to unmask]> + * + * @see EcalConditions + * @see EcalChannel + * @see EcalGain + * @see EcalCalibration + * @see EcalBadChannel + * @see EcalTimeShift + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> + * @author <a href="mailto:[log in to unmask]">Omar Moreno</a> */ public class EcalConditionsConverter implements ConditionsConverter<EcalConditions> { - static Logger logger = LogUtil.create(AbstractSvtConditionsConverter.class); - - protected EcalChannelCollection getEcalChannelCollection(DatabaseConditionsManager manager) { + /** + * Get the default {@link EcalChannel} collection. + * @param manager The conditions manager. + * @return The default ECAL channel object collection. + */ + protected EcalChannelCollection getEcalChannelCollection(final DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalChannelCollection.class, "ecal_channels").getCachedData(); } - - protected EcalGainCollection getEcalGainCollection(DatabaseConditionsManager manager) { + + /** + * Get the default {@link EcalGain} collection. + * @param manager The conditions manager. + * @return The ECAL channel gain collection. + */ + protected EcalGainCollection getEcalGainCollection(final DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalGainCollection.class, "ecal_gains").getCachedData(); } - - protected ConditionsSeries<EcalBadChannel, EcalBadChannelCollection> getEcalBadChannelSeries(DatabaseConditionsManager manager) { + + /** + * Get the default collections of {@link EcalBadChannel} objects. + * @param manager The conditions manager. + * @return The collections of ECAL bad channel objects. + */ + protected ConditionsSeries<EcalBadChannel, EcalBadChannelCollection> getEcalBadChannelSeries(final DatabaseConditionsManager manager) { return manager.getConditionsSeries(EcalBadChannelCollection.class, "ecal_bad_channels"); } - + + /** + * Get the default {@link EcalCalibration} collection. + * @param manager The conditions manager. + * @return The collection of ECAL channel calibration objects. + */ protected EcalCalibrationCollection getEcalCalibrationCollection(DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalCalibrationCollection.class, "ecal_calibrations").getCachedData(); } + /** + * Get the default {@link EcalTimeShift} collection. + * @param manager The conditions manager. + * @return The collection of ECAL time shift objects. + */ protected EcalTimeShiftCollection getEcalTimeShiftCollection(DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalTimeShiftCollection.class, "ecal_time_shifts").getCachedData(); } /** - * Create ECAL conditions object containing all data for the current run. + * Create combined ECAL conditions object containing all data for the current run. + * @param manager The conditions manager. + * @param name The conditions set name (unused but must satisfy conditions API). */ - public EcalConditions getData(ConditionsManager manager, String name) { + public final EcalConditions getData(ConditionsManager manager, String name) { - DatabaseConditionsManager databaseConditionsManager = (DatabaseConditionsManager) manager; + final DatabaseConditionsManager databaseConditionsManager = (DatabaseConditionsManager) manager; // Get the ECal channel map from the conditions database - EcalChannelCollection channels = getEcalChannelCollection(databaseConditionsManager); + final EcalChannelCollection channels = getEcalChannelCollection(databaseConditionsManager); // Create the ECal conditions object that will be used to encapsulate // ECal conditions collections - Detector detector = databaseConditionsManager.getDetectorObject(); - EcalConditions conditions = new EcalConditions(detector.getSubdetector(databaseConditionsManager.getEcalName())); + final Detector detector = databaseConditionsManager.getDetectorObject(); + final EcalConditions conditions = new EcalConditions(detector.getSubdetector(databaseConditionsManager.getEcalName())); // Set the channel map. conditions.setChannelCollection(channels); // Get the ECal gains from the conditions database and add them to the // conditions set - EcalGainCollection gains = getEcalGainCollection(databaseConditionsManager); + final EcalGainCollection gains = getEcalGainCollection(databaseConditionsManager); for (EcalGain gain : gains) { - ChannelId channelId = new ChannelId(new int[] { gain.getChannelId() }); - EcalChannel channel = channels.findChannel(channelId); + final ChannelId channelId = new ChannelId(new int[] { gain.getChannelId() }); + final EcalChannel channel = channels.findChannel(channelId); conditions.getChannelConstants(channel).setGain(gain); } - ConditionsSeries<EcalBadChannel, EcalBadChannelCollection> badChannelSeries = + final ConditionsSeries<EcalBadChannel, EcalBadChannelCollection> badChannelSeries = getEcalBadChannelSeries(databaseConditionsManager); // FIXME: How to get EcalBadChannelCollection here instead for the collection type? // API of ConditionsSeries and ConditionsSeriesConverter needs to be changed! for (ConditionsObjectCollection<EcalBadChannel> badChannels : badChannelSeries) { for (EcalBadChannel badChannel : badChannels) { - ChannelId channelId = new ChannelId(new int[] { badChannel.getChannelId() }); - EcalChannel channel = channels.findChannel(channelId); + final ChannelId channelId = new ChannelId(new int[] { badChannel.getChannelId() }); + final EcalChannel channel = channels.findChannel(channelId); conditions.getChannelConstants(channel).setBadChannel(true); } } // Get the ECal calibrations from the conditions database and add them // to the conditions set. - EcalCalibrationCollection calibrations = getEcalCalibrationCollection(databaseConditionsManager); + final EcalCalibrationCollection calibrations = getEcalCalibrationCollection(databaseConditionsManager); for (EcalCalibration calibration : calibrations) { - ChannelId channelId = new ChannelId(new int[] { calibration.getChannelId() }); - EcalChannel channel = channels.findChannel(channelId); + final ChannelId channelId = new ChannelId(new int[] { calibration.getChannelId() }); + final EcalChannel channel = channels.findChannel(channelId); conditions.getChannelConstants(channel).setCalibration(calibration); } @@ -102,10 +129,10 @@ if (databaseConditionsManager.hasConditionsRecord("ecal_time_shifts")) { EcalTimeShiftCollection timeShifts = getEcalTimeShiftCollection(databaseConditionsManager); for (EcalTimeShift timeShift : timeShifts) { - ChannelId channelId = new ChannelId(new int[] {timeShift.getChannelId()}); - EcalChannel channel = channels.findChannel(channelId); + final ChannelId channelId = new ChannelId(new int[] {timeShift.getChannelId()}); + final EcalChannel channel = channels.findChannel(channelId); conditions.getChannelConstants(channel).setTimeShift(timeShift); - } + } } else { DatabaseConditionsManager.getLogger().warning("no ecal_time_shifts collection found"); } @@ -118,7 +145,7 @@ * Get the type handled by this converter. * @return The type handled by this converter. */ - public Class<EcalConditions> getType() { + public final Class<EcalConditions> getType() { return EcalConditions.class; } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsUtil.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsUtil.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalConditionsUtil.java Thu Apr 2 18:14:47 2015 @@ -9,18 +9,21 @@ /** * This is a set of utility methods for the ECAL that use the database * conditions system. - * - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ public final class EcalConditionsUtil { + /** + * The combined ECAL conditions object. + */ private EcalConditions conditions; /** * Constructor which uses external reference to conditions object. * @param conditions The ECAL conditions object. */ - public EcalConditionsUtil(EcalConditions conditions) { + public EcalConditionsUtil(final EcalConditions conditions) { this.conditions = conditions; } @@ -36,21 +39,20 @@ * Find a channel object from a cell ID, e.g. from Monte Carlo data. * @param helper The identifier helper of the hit. * @param cellId The cell ID of the hit. - * @return The corresponding ECAL channel found from the physical ID - * information. + * @return The corresponding ECAL channel found from the physical ID information. */ - public EcalChannel findChannel(IIdentifierHelper helper, long cellId) { + public EcalChannel findChannel(final IIdentifierHelper helper, final long cellId) { // Make an ID object from hit ID. - IIdentifier id = new Identifier(cellId); + final IIdentifier id = new Identifier(cellId); // Get physical field values. - int system = helper.getValue(id, "system"); - int x = helper.getValue(id, "ix"); - int y = helper.getValue(id, "iy"); + final int system = helper.getValue(id, "system"); + final int x = helper.getValue(id, "ix"); + final int y = helper.getValue(id, "iy"); // Create an ID to search for in channel collection. - GeometryId geometryId = new GeometryId(helper, new int[] { system, x, y }); + final GeometryId geometryId = new GeometryId(helper, new int[] { system, x, y }); // Find the ECAL channel and return the crate number. return conditions.getChannelCollection().findChannel(geometryId); @@ -62,7 +64,7 @@ * @param cellId The cell ID of the hit. * @return The crate number of the channel. */ - public int getCrate(IIdentifierHelper helper, long cellId) { + public int getCrate(final IIdentifierHelper helper, final long cellId) { return findChannel(helper, cellId).getCrate(); } @@ -72,7 +74,7 @@ * @param cellId The cell ID of the hit. * @return The slot number of the channel. */ - public int getSlot(IIdentifierHelper helper, long cellId) { + public int getSlot(final IIdentifierHelper helper, final long cellId) { return findChannel(helper, cellId).getSlot(); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCrystalChannelMap.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCrystalChannelMap.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalCrystalChannelMap.java Thu Apr 2 18:14:47 2015 @@ -10,56 +10,64 @@ /** * This is a convenience utility for associating the geometric crystal - * objects with the conditions system channel information and vice versa. + * objects with the conditions system channel information and vice versa. * - * @author Jeremy McCormick <[log in to unmask]> + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ final class EcalCrystalChannelMap { + + /** + * Map of crystal to channel. + */ + Map<EcalCrystal, EcalChannel> crystalMap = new HashMap<EcalCrystal, EcalChannel>(); - Map<EcalCrystal, EcalChannel> crystalMap = new HashMap<EcalCrystal, EcalChannel>(); + /** + * Map of channel to crystal. + */ Map<EcalChannel, EcalCrystal> channelMap = new HashMap<EcalChannel, EcalCrystal>(); - + /** * Creates the map between crystals and channels. * @param api The ECAL API. * @param channels The list of channels. */ - EcalCrystalChannelMap(HPSEcalAPI api, EcalChannelCollection channels) { - + EcalCrystalChannelMap(final HPSEcalAPI api, final EcalChannelCollection channels) { + // Map crystals to channels. for (EcalCrystal crystal : api.getCrystals()) { - EcalChannel channel = channels.findGeometric(crystal.getIdentifier().getValue()); + final EcalChannel channel = channels.findGeometric(crystal.getIdentifier().getValue()); if (channel == null) { throw new RuntimeException("ECAL channel was not found for ID: " + crystal.getExpandedIdentifier()); } crystalMap.put(crystal, channel); } - + // Map channels to crystals. for (EcalChannel channel : channels) { - EcalCrystal crystal = api.getCrystal(channel.getX(), channel.getY()); + final EcalCrystal crystal = api.getCrystal(channel.getX(), channel.getY()); if (crystal == null) { - throw new RuntimeException("ECAl crystal was not found for channel X Y: " + channel.getX() + " " + channel.getY()); + throw new RuntimeException("ECAl crystal was not found for channel X Y: " + + channel.getX() + " " + channel.getY()); } channelMap.put(channel, crystal); } } - + /** * Get a channel from a crystal. * @param crystal The geometry object. * @return The channel information or null if does not exist. */ - EcalChannel getEcalChannel(EcalCrystal crystal) { + EcalChannel getEcalChannel(final EcalCrystal crystal) { return crystalMap.get(crystal); } - + /** * Get a channel from a crystal. * @param crystal The geometry object. * @return The channel information or null if does not exist. */ - EcalCrystal getEcalCrystal(EcalChannel channel) { + EcalCrystal getEcalCrystal(final EcalChannel channel) { return channelMap.get(channel); } } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalGain.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalGain.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalGain.java Thu Apr 2 18:14:47 2015 @@ -2,30 +2,47 @@ import java.util.Comparator; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; import org.hps.conditions.database.Table; /** - * A simplistic representation of gain values from the ECal conditions database. + * A per channel ECAL gain value. * - * @author Jeremy McCormick <[log in to unmask]> + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -@Table(names = {"ecal_gains", "test_run_ecal_gains", "ecal_hardware_gains"}) +@Table(names = { "ecal_gains", "test_run_ecal_gains", "ecal_hardware_gains" }) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class EcalGain extends AbstractConditionsObject { +public final class EcalGain extends BaseConditionsObject { - public static class EcalGainCollection extends AbstractConditionsObjectCollection<EcalGain> { - - public AbstractConditionsObjectCollection<EcalGain> sorted() { + /** + * The collection implementation for this class. + */ + @SuppressWarnings("serial") + public static final class EcalGainCollection extends BaseConditionsObjectCollection<EcalGain> { + + /** + * Sort and return a copy of the collection. + * @return A sorted copy of the collection. + */ + public BaseConditionsObjectCollection<EcalGain> sorted() { return sorted(new ChannelIdComparator()); } - + + /** + * Comparison implementation by channel ID. + */ class ChannelIdComparator implements Comparator<EcalGain> { - public int compare(EcalGain o1, EcalGain o2) { + /** + * Compare two objects by their channel ID. + * @param o1 The first object. + * @param o2 The second object. + * @return -1, 0 or 1 if first channel ID is less than, equal to, or greater than second. + */ + public int compare(final EcalGain o1, final EcalGain o2) { if (o1.getChannelId() < o2.getChannelId()) { return -1; } else if (o1.getChannelId() > o2.getChannelId()) { @@ -34,26 +51,27 @@ return 0; } } - + } } - - + /** * Get the gain value in units of MeV/ADC count. + * * @return The gain value. */ - @Field(names = {"gain"}) + @Field(names = { "gain" }) public double getGain() { return getFieldValue("gain"); } /** * Get the ECal channel ID. + * * @return The ECal channel ID. */ - @Field(names = {"ecal_channel_id"}) + @Field(names = { "ecal_channel_id" }) public int getChannelId() { return getFieldValue("ecal_channel_id"); } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLed.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLed.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLed.java Thu Apr 2 18:14:47 2015 @@ -2,8 +2,8 @@ import java.util.Comparator; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -13,21 +13,33 @@ /** * A conditions class for representing the setup of the LED system in the ECAL * for one channel. - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Table(names = "ecal_leds") @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public class EcalLed extends AbstractConditionsObject { +public final class EcalLed extends BaseConditionsObject { /** * Generic collection class for these objects. */ - public static class EcalLedCollection extends AbstractConditionsObjectCollection<EcalLed> { - public AbstractConditionsObjectCollection<EcalLed> sorted() { + public static class EcalLedCollection extends BaseConditionsObjectCollection<EcalLed> { + + /** + * Sort and return a copy of this collection. + * @return The sorted copy. + */ + public BaseConditionsObjectCollection<EcalLed> sorted() { return sorted(new ChannelIdComparator()); } + /** + * Comparison implementation by channel ID. + */ class ChannelIdComparator implements Comparator<EcalLed> { + /** + * Compare two objects by channel ID. + */ public int compare(EcalLed o1, EcalLed o2) { if (o1.getEcalChannelId() < o2.getEcalChannelId()) { return -1; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLedCalibration.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLedCalibration.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalLedCalibration.java Thu Apr 2 18:14:47 2015 @@ -1,28 +1,43 @@ package org.hps.conditions.ecal; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; import org.hps.conditions.database.Table; +/** + * ECAL LED calibration information per channel. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> + */ @Table(names = "ecal_led_calibrations") @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public class EcalLedCalibration extends AbstractConditionsObject { - +public final class EcalLedCalibration extends BaseConditionsObject { + /** * Generic collection class for these objects. */ - public static class EcalLedCalibrationCollection extends AbstractConditionsObjectCollection<EcalLedCalibration> { + @SuppressWarnings("serial") + public static class EcalLedCalibrationCollection extends BaseConditionsObjectCollection<EcalLedCalibration> { } - - public EcalLedCalibration() { + + /** + * Class constructor. + */ + public EcalLedCalibration() { } - - public EcalLedCalibration(int channelId, double mean, double rms) { + + /** + * Fully qualified constructor. + * @param channelId The ECAL channel ID (not the LED channel ID). + * @param ledResponse The mean of the LED response. + * @param rms The RMS of the LED response. + */ + public EcalLedCalibration(int channelId, double ledResponse, double rms) { this.setFieldValue("ecal_channel_id", channelId); - this.setFieldValue("led_response", mean); + this.setFieldValue("led_response", ledResponse); this.setFieldValue("rms", rms); } /** @@ -44,11 +59,11 @@ } /** - * Get the RMS of the LED response + * Get the RMS of the LED response. * @return The RMS of the LED response. */ @Field(names = {"rms"}) public int getRms() { return getFieldValue("rms"); } -} +} Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalTimeShift.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalTimeShift.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/EcalTimeShift.java Thu Apr 2 18:14:47 2015 @@ -2,31 +2,45 @@ import java.util.Comparator; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; import org.hps.conditions.database.Table; -import org.hps.conditions.ecal.EcalCalibration.EcalCalibrationCollection.ChannelIdComparator; /** * This class represents a time shift calibration value for an ECAL channel. - * @author Jeremy McCormick <[log in to unmask]> + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ @Table(names = {"ecal_time_shifts", "test_run_ecal_time_shifts"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class EcalTimeShift extends AbstractConditionsObject { +public final class EcalTimeShift extends BaseConditionsObject { /** * A collection of {@link EcalTimeShift} objects. */ - public static class EcalTimeShiftCollection extends AbstractConditionsObjectCollection<EcalTimeShift> { - public AbstractConditionsObjectCollection<EcalTimeShift> sorted() { + public static class EcalTimeShiftCollection extends BaseConditionsObjectCollection<EcalTimeShift> { + + /** + * Sort and return a copy of the collection. + * @return The sorted copy of the collection. + */ + public BaseConditionsObjectCollection<EcalTimeShift> sorted() { return sorted(new ChannelIdComparator()); } - + + /** + * Compare two objects by their channel ID. + */ class ChannelIdComparator implements Comparator<EcalTimeShift> { + /** + * Compare two objects by channel ID. + * @param o1 The first object. + * @param o2 The second object. + * @return -1, 0 or 1 if first channel ID is less than, equal to, or greater than second. + */ public int compare(EcalTimeShift o1, EcalTimeShift o2) { if (o1.getChannelId() < o2.getChannelId()) { return -1; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/TestRunEcalConditionsConverter.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/TestRunEcalConditionsConverter.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/TestRunEcalConditionsConverter.java Thu Apr 2 18:14:47 2015 @@ -11,28 +11,49 @@ /** * This class loads all Test Run ECAL conditions into an {@link EcalConditions} object * from the database. - * - * @author Jeremy McCormick <[log in to unmask]> - * @author Omar Moreno <[log in to unmask]> + * <p> + * The default names are overridden to use tables that contain Test Run data, only. + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> + * @author <a href="mailto:[log in to unmask]">Omar Moreno</a> */ public final class TestRunEcalConditionsConverter extends EcalConditionsConverter { - + + /** + * Get the {@link EcalChannel} collection for Test Run. + * @return The Test Run ECAL channel collection. + */ protected EcalChannelCollection getEcalChannelCollection(DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalChannelCollection.class, "test_run_ecal_channels").getCachedData(); } - + /** + * Get the {@link EcalGain} collection for Test Run. + * @return The Test Run ECAL gain collection. + */ protected EcalGainCollection getEcalGainCollection(DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalGainCollection.class, "test_run_ecal_gains").getCachedData(); } + /** + * Get the collections of {@link EcalBadChannel} objects for Test Run. + * @return The Test Run bad channel collections. + */ protected ConditionsSeries<EcalBadChannel, EcalBadChannelCollection> getEcalBadChannelSeries(DatabaseConditionsManager manager) { return manager.getConditionsSeries(EcalBadChannelCollection.class, "test_run_ecal_bad_channels"); } - + + /** + * Get the {@link EcalCalibration} collection for Test Run. + * @return The Test Run ECAL calibration collection. + */ protected EcalCalibrationCollection getEcalCalibrationCollection(DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalCalibrationCollection.class, "test_run_ecal_calibrations").getCachedData(); } - + + /** + * Get the {@link EcalTimeShift} collection for Test Run. + * @return The Test Run ECAL time shift collection. + */ protected EcalTimeShiftCollection getEcalTimeShiftCollection(DatabaseConditionsManager manager) { return manager.getCachedConditions(EcalTimeShiftCollection.class, "test_run_ecal_time_shifts").getCachedData(); } Modified: java/trunk/conditions/src/main/java/org/hps/conditions/ecal/package-info.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/ecal/package-info.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/ecal/package-info.java Thu Apr 2 18:14:47 2015 @@ -9,13 +9,18 @@ * these channels. * <p> * The {@link EcalCalibration} contains the pedestal and noise values for a channel, - * which are the mean and the standard deviation of the digitized pre-amp output. + * which are the mean and the standard deviation of the digitized preamplifier output. * <p> * The {@link EcalGain} is the channel gain in units of MeV/ADC counts. * <p> + * The {@link EcalTimeShift} is a time shift in the electronics response. + * <p> + * The {@link EcalLedCalibration} is calibration information for the LED attached to + * an ECAL channel. + * <p> * The energy of a hit is reconstructed by multiplying the gain by the pedestal-subtracted - * ADC integral (e.g. in Test Run 2012 data). + * ADC integral (e.g. in Test Run 2012 data). * * @author Jeremy McCormick <[log in to unmask]> */ -package org.hps.conditions.ecal; +package org.hps.conditions.ecal; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/package-info.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/package-info.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/package-info.java Thu Apr 2 18:14:47 2015 @@ -1,9 +1,11 @@ /** - * The HPS conditions module provides facilities for accessing time dependent conditions - * for a detector at runtime using a framework built on the LCSim conditions system. - * The {@link DatabaseConditionsReader} has a set of converters for reading data from - * tables using SQL queries and creating appropriate, typed objects for them. - * - * @author Jeremy McCormick <[log in to unmask]> + * The HPS conditions module provides facilities for accessing time dependent conditions for a detector at runtime + * using a framework built on the LCSim conditions system. The {@link DatabaseConditionsReader} has a set of + * converters for reading data from tables using SQL queries and creating appropriate, typed objects for them. + * + * @see org.hps.conditions.api + * @see org.hps.conditions.database + * + * @author <a href="mailto:[log in to unmask]">Jeremy McCormick</a> */ -package org.hps.conditions; +package org.hps.conditions; Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtChannel.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtChannel.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtChannel.java Thu Apr 2 18:14:47 2015 @@ -4,8 +4,8 @@ import java.util.HashMap; import java.util.Map; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Field; import org.hps.util.Pair; @@ -14,12 +14,12 @@ * * @author Omar Moreno <[log in to unmask]> */ -public class AbstractSvtChannel extends AbstractConditionsObject { +public class AbstractSvtChannel extends BaseConditionsObject { // TODO: Put constants into their own class public static final int MAX_NUMBER_OF_SAMPLES = 6; - public static abstract class AbstractSvtChannelCollection<T extends AbstractSvtChannel> extends AbstractConditionsObjectCollection<T> { + public static abstract class AbstractSvtChannelCollection<T extends AbstractSvtChannel> extends BaseConditionsObjectCollection<T> { Map<Integer, T> channelMap = new HashMap<Integer, T>(); Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtConditions.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtConditions.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtConditions.java Thu Apr 2 18:14:47 2015 @@ -10,7 +10,7 @@ /** * Abstract class providing some of the common functionality used to define an * SVT conditions object - * + * * @author Omar Moreno <[log in to unmask]> * */ Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtDaqMapping.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtDaqMapping.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtDaqMapping.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Field; import org.hps.util.Pair; import org.lcsim.detector.tracker.silicon.HpsSiSensor; @@ -12,7 +12,7 @@ * * @author Omar Moreno <[log in to unmask]> */ -public abstract class AbstractSvtDaqMapping extends AbstractConditionsObject { +public abstract class AbstractSvtDaqMapping extends BaseConditionsObject { /** * Flag values for top or bottom half. @@ -26,7 +26,7 @@ public static final String AXIAL = "A"; public static final String STEREO = "S"; - public static abstract class AbstractSvtDaqMappingCollection<T extends AbstractSvtDaqMapping> extends AbstractConditionsObjectCollection<T> { + public static abstract class AbstractSvtDaqMappingCollection<T extends AbstractSvtDaqMapping> extends BaseConditionsObjectCollection<T> { /** Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtT0Shift.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtT0Shift.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/AbstractSvtT0Shift.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Field; import org.hps.util.Pair; @@ -11,9 +11,9 @@ * * @author Omar Moreno <[log in to unmask]> */ -public class AbstractSvtT0Shift extends AbstractConditionsObject { +public class AbstractSvtT0Shift extends BaseConditionsObject { - public static abstract class AbstractSvtT0ShiftCollection<T extends AbstractSvtT0Shift> extends AbstractConditionsObjectCollection<T> { + public static abstract class AbstractSvtT0ShiftCollection<T extends AbstractSvtT0Shift> extends BaseConditionsObjectCollection<T> { /** * Get the t0 shift associated with a given DAQ pair Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtAlignmentConstant.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtAlignmentConstant.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtAlignmentConstant.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -22,9 +22,9 @@ */ @Table(names = "svt_alignments") @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_UPDATED) -public final class SvtAlignmentConstant extends AbstractConditionsObject { +public final class SvtAlignmentConstant extends BaseConditionsObject { - public static class SvtAlignmentConstantCollection extends AbstractConditionsObjectCollection<SvtAlignmentConstant> { + public static class SvtAlignmentConstantCollection extends BaseConditionsObjectCollection<SvtAlignmentConstant> { } /** Top or bottom half. */ Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtBadChannel.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtBadChannel.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtBadChannel.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -9,9 +9,9 @@ @Table(names = {/*"svt_bad_channels",*/ "test_run_svt_bad_channels"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class SvtBadChannel extends AbstractConditionsObject { +public final class SvtBadChannel extends BaseConditionsObject { - public static class SvtBadChannelCollection extends AbstractConditionsObjectCollection<SvtBadChannel> { + public static class SvtBadChannelCollection extends BaseConditionsObjectCollection<SvtBadChannel> { } @Field(names = {"svt_channel_id"}) Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtCalibration.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtCalibration.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtCalibration.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -17,9 +17,9 @@ */ @Table(names = {"svt_calibrations", "test_run_svt_calibrations"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_UPDATED) -public final class SvtCalibration extends AbstractConditionsObject { +public final class SvtCalibration extends BaseConditionsObject { - public static class SvtCalibrationCollection extends AbstractConditionsObjectCollection<SvtCalibration> { + public static class SvtCalibrationCollection extends BaseConditionsObjectCollection<SvtCalibration> { } /** Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConditionsLoader.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConditionsLoader.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConditionsLoader.java Thu Apr 2 18:14:47 2015 @@ -114,7 +114,7 @@ // Set the collection ID int collectionID = DatabaseConditionsManager.getInstance().getNextCollectionID(SvtConditionsLoader.CALIBRATIONS_TABLE_NAME); - calibrations.setCollectionId(collectionID); + calibrations.setCollectionID(collectionID); logger.info("Using collection ID " + collectionID); // Load the calibrations @@ -155,7 +155,7 @@ // Set the collection ID int collectionID = DatabaseConditionsManager.getInstance().getNextCollectionID(SvtConditionsLoader.DAQ_MAP_TABLE_NAME); - daqMapping.setCollectionId(collectionID); + daqMapping.setCollectionID(collectionID); logger.info("Using collection ID " + collectionID); // Load the DAQ map @@ -184,7 +184,7 @@ // Set the collection ID collectionID = DatabaseConditionsManager.getInstance().getNextCollectionID(SvtConditionsLoader.SVT_CHANNELS_TABLE_NAME); - svtChannels.setCollectionId(collectionID); + svtChannels.setCollectionID(collectionID); logger.info("Using collection ID " + collectionID); svtChannels.insert(); Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConfiguration.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConfiguration.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtConfiguration.java Thu Apr 2 18:14:47 2015 @@ -5,8 +5,8 @@ import java.io.IOException; import java.io.InputStream; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -22,9 +22,9 @@ */ @Table(names = {"svt_configurations"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_UPDATED) -public class SvtConfiguration extends AbstractConditionsObject { +public class SvtConfiguration extends BaseConditionsObject { - public static class SvtConfigurationCollection extends AbstractConditionsObjectCollection<SvtConfiguration> { + public static class SvtConfigurationCollection extends BaseConditionsObjectCollection<SvtConfiguration> { } /** Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtGain.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtGain.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtGain.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -13,9 +13,9 @@ */ @Table(names = {"svt_gains", "test_run_svt_gains"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class SvtGain extends AbstractConditionsObject { +public final class SvtGain extends BaseConditionsObject { - public static class SvtGainCollection extends AbstractConditionsObjectCollection<SvtGain> { + public static class SvtGainCollection extends BaseConditionsObjectCollection<SvtGain> { } /** Modified: java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtShapeFitParameters.java ============================================================================= --- java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtShapeFitParameters.java (original) +++ java/trunk/conditions/src/main/java/org/hps/conditions/svt/SvtShapeFitParameters.java Thu Apr 2 18:14:47 2015 @@ -1,7 +1,7 @@ package org.hps.conditions.svt; -import org.hps.conditions.api.AbstractConditionsObject; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObject; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.Converter; import org.hps.conditions.database.Field; import org.hps.conditions.database.MultipleCollectionsAction; @@ -15,9 +15,9 @@ */ @Table(names = {"svt_shape_fit_parameters", "test_run_svt_shape_fit_parameters"}) @Converter(multipleCollectionsAction = MultipleCollectionsAction.LAST_CREATED) -public final class SvtShapeFitParameters extends AbstractConditionsObject { +public final class SvtShapeFitParameters extends BaseConditionsObject { - public static class SvtShapeFitParametersCollection extends AbstractConditionsObjectCollection<SvtShapeFitParameters> { + public static class SvtShapeFitParametersCollection extends BaseConditionsObjectCollection<SvtShapeFitParameters> { } /** Modified: java/trunk/conditions/src/test/java/org/hps/conditions/EngRunConditionsTest.java ============================================================================= --- java/trunk/conditions/src/test/java/org/hps/conditions/EngRunConditionsTest.java (original) +++ java/trunk/conditions/src/test/java/org/hps/conditions/EngRunConditionsTest.java Thu Apr 2 18:14:47 2015 @@ -9,7 +9,7 @@ import junit.framework.TestCase; -import org.hps.conditions.api.AbstractConditionsObjectCollection; +import org.hps.conditions.api.BaseConditionsObjectCollection; import org.hps.conditions.database.DatabaseConditionsManager; import org.hps.conditions.ecal.EcalCalibration.EcalCalibrationCollection; import org.hps.conditions.ecal.EcalChannel; @@ -63,7 +63,7 @@ loop.loop(100); } - static void checkRunNumbers(AbstractConditionsObjectCollection<?> collection) { + static void checkRunNumbers(BaseConditionsObjectCollection<?> collection) { assertTrue("Run start out of range.", collection.getConditionsRecord().getRunStart() >= runStart); assertTrue("Run end out of range.", collection.getConditionsRecord().getRunEnd() <= runEnd); }